@magic/test
Common Pitfalls
Avoid these common mistakes when writing tests:
1. Forgetting to Return in Async Tests
The test finishes before the promise resolves. Always return the promise:
# Wrong: promise resolves before test checks resultexport default {fn: async () => {const result = await someAsyncFunction()// missing return!},expect: true,}# Correct:export default {fn: async () => {return await someAsyncFunction()},expect: true,}
2. Not Wrapping Callback Functions
# Wrong: function gets called immediatelyexport default {fn: doSomething(), // executes immediately!expect: true,}# Correct: wrap in function to defer executionexport default {fn: () => doSomething(),expect: true,}
3. Mutating Shared State Between Tests
# Wrong: counter persists between testslet counter = 0export default [{ fn: () => ++counter, expect: 1 },{ fn: () => ++counter, expect: 2 }, // fails! counter is now 1]# Correct: use beforeEach to reset stateexport default {beforeEach: () => { counter = 0 },tests: [{ fn: () => ++counter, expect: 1 },{ fn: () => ++counter, expect: 1 }, // passes - reset before each],}
4. Using the Wrong Equality Check
# Wrong: checks reference equalityexport default {fn: () => [1, 2, 3],expect: [1, 2, 3], // fails! different arrays}# Correct: use @magic/types for deep comparisonimport { is } from '@magic/test'export default {fn: () => [1, 2, 3],expect: is.deep.equal([1, 2, 3]),}
5. Not Awaiting Async Operations
# Wrong: test finishes before promise resolvesexport default {fn: () => {setTimeout(() => {// This never gets checked!}, 100)},expect: true,}# Correct: return the promiseexport default {fn: () => new Promise(resolve => {setTimeout(() => resolve(true), 100)}),expect: true,}# Or use the promise helper:import { promise } from '@magic/test'export default {fn: promise(cb => setTimeout(() => cb(null, true), 100)),expect: true,}
6. Incorrect Hook Usage
# Wrong: before/after hooks on individual tests, not suitesexport default [{fn: () => true,beforeAll: () => {}, // wrong! beforeAll is for suitesafterAll: () => {},expect: true,},]# Correct: hooks at suite levelexport default {beforeAll: () => {},afterAll: () => {},tests: [{ fn: () => true, expect: true },],}