memlab-memory-tests
Что он делает
Он показывает, как писать модульные тесты, которые проверяют, что освобождённый объект исчез, и как запускать сценарии memlab в задаче тестирования, которая падает при обнаружении утечек. Он нужен разработчикам, которые хотят, чтобы проверки утечек оставались в их наборе тестов.
Когда использовать
- ✓Когда вы хотите тест, который падает, если объект не освобождён после dispose.
- ✓Когда вы хотите, чтобы проверка браузерного сценария на утечки работала в непрерывной интеграции.
- ✓Когда у вас есть тесты на Playwright, Cypress или Puppeteer и вы хотите проверить их память.
Ссылка на скилл
https://github.com/meta/memlab/blob/main/plugins/memlab/skills/memlab-memory-tests/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Добавь тест Jest, который падает, если мой класс Widget всё ещё в памяти после вызова dispose.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Агент помечает объект, освобождает его, снимает снимок кучи и проверяет, что помеченного объекта больше нет. Для браузерных сценариев он запускает сценарий memlab, который проваливает сборку при обнаружении утечек.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с 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
Частые вопросы
Какие инструменты тестирования поддерживаются?
Пример для Node.js использует Jest, а скилл отмечает, что node:test и Mocha работают так же.
Какой пакет нужен для проверок Node.js?
Пакет @memlab/core, установленный как зависимость для разработки.
Можно ли проверять существующие сквозные тесты?
Да. Скилл охватывает снятие снимков из существующих тестов Playwright, Cypress или Puppeteer.
Подробности
Оригинальное описание автора
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
Популярность
- Звёзды на GitHub
- 5.1k
- Место в рейтинге
- #15058
- Лицензия
- MIT
- Обновлён
- 31.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
memlab-analyze-heap-snapshot
5.1kПомогает агенту находить утечки памяти в JavaScript-приложении, анализируя снимок кучи и объясняя, что удерживает объекты в памяти.
memlab-capture-heap-snapshots
5.1kУчит агента снимать снимки кучи JavaScript из браузера, Node.js, Electron или React Native, чтобы изучить использование памяти.
memlab-find-web-leaks
5.1kПомогает агенту находить утечки памяти на веб-странице, запуская скриптованный тест одного действия и читая созданные им отчёты об утечках.
Похожие скиллы
test-driven-development
311kУчит агента сначала писать падающий тест, увидеть, что он падает, и только затем писать минимальный код, который его проходит, прежде чем создавать любую функцию или исправление.
verification-before-completion
311kУчит агента запускать настоящие проверки и читать их вывод, прежде чем утверждать, что задача, исправление или сборка готовы или проходят.
migrate-to-shoehorn
310kЗаменяет рискованные приведения типов в тестовых файлах на библиотеку shoehorn, чтобы тесты могли использовать неполные данные и проходить проверку типов.