memlab-memory-tests
하는 일
dispose 후 해제된 객체가 사라졌는지 확인하는 단위 테스트를 작성하는 방법과, 누수가 발견되면 실패하는 테스트 작업에서 memlab 시나리오를 실행하는 방법을 보여 줍니다. 누수 검사를 테스트 모음에 유지하고 싶은 개발자를 위한 스킬입니다.
사용하는 경우
- ✓dispose 후에 객체가 해제되지 않으면 실패하는 테스트를 원할 때.
- ✓지속적 통합에서 브라우저 누수 검사를 실행하고 싶을 때.
- ✓기존 Playwright, Cypress, Puppeteer 테스트가 있고 그 메모리를 확인하고 싶을 때.
스킬 링크
https://github.com/meta/memlab/blob/main/plugins/memlab/skills/memlab-memory-tests/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“dispose를 호출한 뒤에도 제 Widget 클래스가 메모리에 남아 있으면 실패하는 Jest 테스트를 추가해 주세요.”
매주 새 스킬 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
- 업데이트
- 2026. 10. 31.
댓글
- …
이 저장소의 다른 스킬
memlab-analyze-heap-snapshot
5.1k에이전트가 힙 스냅샷을 분석해 JavaScript 앱의 메모리 누수를 찾고, 무엇이 객체를 살아 있게 하는지 설명하도록 돕습니다.
memlab-capture-heap-snapshots
5.1k에이전트가 브라우저, Node.js, Electron, React Native에서 JavaScript 힙 스냅샷을 찍도록 안내해, 메모리 사용을 분석할 수 있게 합니다.
memlab-find-web-leaks
5.1k에이전트가 웹 페이지에서 상호작용 하나를 스크립트 테스트로 실행하고 누수 보고서를 읽어 메모리 누수를 찾도록 돕습니다.
비슷한 스킬
test-driven-development
311k에이전트가 기능이나 수정을 만들기 전에 실패하는 테스트를 먼저 쓰고, 그것을 통과시키는 가장 작은 코드를 작성하도록 가르칩니다.
verification-before-completion
311k에이전트가 작업, 수정, 빌드가 완료되었거나 통과했다고 말하기 전에 실제 점검을 실행하고 결과를 읽도록 가르칩니다.
migrate-to-shoehorn
310k테스트 파일의 위험한 타입 캐스팅을 shoehorn 라이브러리로 바꿔, 테스트가 일부 데이터만 써도 타입 검사를 통과하도록 돕습니다.