memlab-memory-tests
Qué hace
Muestra cómo escribir pruebas unitarias que verifican que un objeto liberado ya no existe, y cómo ejecutar escenarios de memlab en un trabajo de pruebas que falla cuando hay fugas. Es para desarrolladores que quieren que las revisiones de memoria formen parte de su suite de pruebas.
Cuándo usarla
- ✓Cuando quieres una prueba que falle si un objeto no se libera después de dispose.
- ✓Cuando quieres que una revisión de fugas en el navegador corra en integración continua.
- ✓Cuando tienes pruebas existentes de Playwright, Cypress o Puppeteer y quieres revisar su memoria.
Link de la skill
https://github.com/meta/memlab/blob/main/plugins/memlab/skills/memlab-memory-tests/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Agrega una prueba de Jest que falle si mi clase Widget sigue en memoria después de llamar a dispose.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
El agente marca el objeto, lo libera, toma una instantánea del heap y comprueba que el objeto marcado ya no está. En los flujos de navegador ejecuta un escenario de memlab que hace fallar la compilación cuando encuentra fugas.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de 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
Preguntas frecuentes
¿Qué herramientas de prueba soporta?
El ejemplo de Node.js usa Jest, y la skill indica que node:test y Mocha funcionan de la misma manera.
¿Qué paquete se necesita para las revisiones de Node.js?
El paquete @memlab/core, instalado como dependencia de desarrollo.
¿Se pueden revisar también las pruebas de extremo a extremo existentes?
Sí. La skill cubre cómo tomar instantáneas desde una prueba existente de Playwright, Cypress o Puppeteer.
Detalles
Descripción original del 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
Popularidad
- Estrellas en GitHub
- 5,1 mil
- Posición en el ranking
- #15058
- Licencia
- MIT
- Actualizada
- 31/10/2026
Comentarios
- …
Más skills de este repositorio
memlab-analyze-heap-snapshot
5,1 milAyuda a tu agente a encontrar fugas de memoria en una app de JavaScript analizando una instantánea del heap y explicando qué mantiene vivos a los objetos.
memlab-capture-heap-snapshots
5,1 milGuía a tu agente para tomar instantáneas del heap de JavaScript desde un navegador, Node.js, Electron o React Native, para estudiar el uso de memoria.
memlab-find-web-leaks
5,1 milAyuda a tu agente a encontrar fugas de memoria en una página web, ejecutando una prueba automatizada de una interacción y leyendo los reportes de fugas que produce.
Skills parecidas
test-driven-development
311 milEnseña a tu agente a escribir primero una prueba que falle, verla fallar y después escribir el código más pequeño que la hace pasar, antes de construir cualquier función o corrección.
verification-before-completion
311 milEnseña a tu agente a ejecutar comprobaciones reales y leer su resultado antes de afirmar que una tarea, una corrección o una compilación está completa o en buen estado.
migrate-to-shoehorn
310 milSustituye los casts de tipo arriesgados de tus archivos de prueba por la librería shoehorn, para que las pruebas usen datos parciales y sigan pasando las comprobaciones de tipos.