memlab-memory-tests
O que ela faz
Ele mostra como escrever testes unitários que verificam se um objeto liberado foi de fato removido, e como executar cenários do memlab em uma tarefa de teste que falha quando encontra vazamentos. É para desenvolvedores que querem verificações de vazamento dentro da suíte de testes.
Quando usar
- ✓Quando você quer um teste que falhe se um objeto não for liberado após o dispose.
- ✓Quando você quer uma verificação de vazamento no navegador rodando na integração contínua.
- ✓Quando você já tem testes do Playwright, Cypress ou Puppeteer e quer verificar a memória deles.
Link da skill
https://github.com/meta/memlab/blob/main/plugins/memlab/skills/memlab-memory-tests/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Adicione um teste com Jest que falhe se minha classe Widget ainda estiver na memória depois que o dispose for chamado.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente marca o objeto, libera ele, tira um heap snapshot e verifica se o objeto marcado sumiu. Para fluxos de navegador, ele executa um cenário do memlab que faz o build falhar quando encontra vazamentos.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
Memory leak tests with memlab
Pick the kind of test from what has to stay leak-free:
| Code under test | Test |
|---|---|
| A Node.js module, class or server code | Heap assertion in a unit test |
| A web UI interaction | memlab scenario run from the test job |
| An existing Playwright, Cypress or Puppeteer test | Snapshots from the existing test |
Node.js heap assertions
takeNodeMinimalHeap() from @memlab/core snapshots the current process and
returns a queryable heap. Assert that the object you released is gone:
// widget.memory.test.js (Jest; node:test and Mocha work the same way)
const {config, takeNodeMinimalHeap, tagObject} = require('@memlab/core');
const {Widget} = require('./widget');
test('Widget is released after dispose()', async () => {
config.muteConsole = true;
let widget = new Widget();
tagObject(widget, 'widget-under-test'); // marks it without changing it
widget.dispose();
widget = null;
const heap = await takeNodeMinimalHeap();
expect(heap.hasObjectWithTag('widget-under-test')).toBe(false);
}, 30000);
npm install --save-dev @memlab/core
tagObject(obj, tag)+heap.hasObjectWithTag(tag)checks one specific instance.heap.hasObjectWithClassName('Widget')checks that no instance of the class is left;heap.getAnyObjectWithClassName('Widget')returns one to inspect.heap.hasObjectWithPropertyName(name)checks for any object with that property.- Drop every reference the test holds (set variables to
null) before taking the heap, or the test itself keeps the object alive. - Taking and parsing a snapshot takes from under a second to many seconds, depending on heap size. Give the test a generous timeout, and keep these tests in their own file so the rest of the suite stays fast.
- For retained sizes, use
takeNodeFullHeap()from@memlab/heap-analysis. The minimal heap skips that computation to parse faster. - When the assertion fails, find out what still holds the object: save a
snapshot with
dumpNodeHeapSnapshot()from@memlab/coreand inspect it (see thememlab-analyze-heap-snapshotskill).
Browser leak tests in CI
Write a scenario for the interaction (see the memlab-find-web-leaks skill),
then run it from the test job with @memlab/api and fail on leaks:
// settings-dialog.memory.test.js
const {run} = require('@memlab/api');
const scenario = require('./scenarios/settings-dialog');
test('settings dialog does not leak', async () => {
const {leaks} = await run({
scenario,
skipWarmup: true, // skip the server warm-up visits
consoleMode: 'CONTINUOUS_TEST', // no progress animation in CI logs
workDir: '/tmp/memlab/settings-dialog', // must exist; keep it as a CI artifact
});
expect(leaks.length).toBe(0);
}, 10 * 60 * 1000);
npm install --save-dev @memlab/api
runreturns{leaks, runResult}.leaksis the list of clustered leak traces; an empty list means no leaks were found. The work directory has the snapshots and browser console output (data/cur/) and the readable traces (data/out/leaks.txt). Upload it from CI so a failure can be investigated.CONTINUOUS_TESTmode skips screenshots and waits an extra 10 seconds after the initial page load. LeaveconsoleModeout when you want screenshots of each step.- Create
workDirbefore callingrun(for example withfs.mkdirSync(dir, {recursive: true})). runlaunches headless Chromium through Puppeteer. On Linux CI images, install Chromium's shared libraries, or setchromiumBinaryto a browser the image already has.- The CLI equivalent is
memlab run --scenario <file> --work-dir <dir> --sc, where--scis the continuous-test console mode. Assert on the result in a script withBrowserInteractionResultReaderandfindLeaksfrom@memlab/api. - Keep one interaction per scenario, so a failure points at one feature.
Snapshots from an existing E2E test
Take three Chromium heap snapshots in the existing test: baseline (before the
interaction), target (after it) and final (after undoing it). The
memlab-capture-heap-snapshots skill has a CDP helper for Puppeteer and
Playwright. Then:
const {findLeaksBySnapshotFilePaths} = require('@memlab/api');
test('the flow under test does not leak', async () => {
// ...drive the flow and write the
Perguntas frequentes
Quais ferramentas de teste ela suporta?
O exemplo para Node.js usa Jest, e a skill observa que node:test e Mocha funcionam da mesma forma.
Qual pacote é necessário para as verificações em Node.js?
O pacote @memlab/core, instalado como dependência de desenvolvimento.
Testes de ponta a ponta existentes também podem ser verificados?
Sim. A skill cobre como tirar snapshots a partir de um teste existente do Playwright, Cypress ou Puppeteer.
Detalhes
Descrição original do autor
Write automated memory leak tests with memlab. Use it for Node.js unit tests that assert an object was garbage collected (takeNodeMinimalHeap, tagObject, hasObjectWithClassName), for browser leak tests in CI that run a memlab scenario through @memlab/api and fail when leaks are found, and for checking heap snapshots from Playwright, Cypress or Puppeteer tests. Use when the user wants a regression test for a memory leak, asks how to assert that memory is released, or wants memory leak checks in Jest, Mocha, node:test or a CI pipeline.
repo: meta/memlab
Popularidade
- Estrelas no GitHub
- 5,1 mil
- Posição no ranking
- #15058
- Licença
- MIT
- Atualizada em
- 31/10/2026
Comentários
- …
Mais skills deste repositório
memlab-analyze-heap-snapshot
5,1 milAjuda seu agente a encontrar vazamentos de memória em uma aplicação JavaScript, analisando um heap snapshot e explicando o que mantém os objetos vivos.
memlab-capture-heap-snapshots
5,1 milOrienta seu agente a capturar heap snapshots de JavaScript em um navegador, Node.js, Electron ou React Native, para que você possa estudar o uso de memória.
memlab-find-web-leaks
5,1 milAjuda seu agente a encontrar vazamentos de memória em uma página web, executando um teste roteirizado de uma interação e lendo os relatórios de vazamento que ele produz.
Skills parecidas
test-driven-development
311 milEnsina seu agente a escrever primeiro um teste que falha, ver a falha e depois escrever o menor código que passa, antes de criar qualquer funcionalidade ou correção.
verification-before-completion
311 milEnsina seu agente a rodar verificações reais e ler a saída antes de afirmar que uma tarefa, correção ou build está concluído ou passando.
migrate-to-shoehorn
310 milSubstitui conversões de tipo arriscadas nos seus arquivos de teste pela biblioteca shoehorn, para que os testes usem dados parciais e ainda passem na checagem de tipos.