Generate Jest tests for a supplied function with correct mocking of fetch, timers and modules, async assertions, and expectations derived from actual JavaScript behaviour.
Write Jest unit tests for the function below. Derive expected values from what the code actually does in JavaScript, mock external effects, and match the project's module and TypeScript setup.
## Inputs
Function source and file path: [CODE]
Intended behaviour or specification, if it differs from the code: [SPEC]
Jest version and config (testEnvironment, transform such as babel-jest or ts-jest, CommonJS or ESM): [JEST_SETUP]
External dependencies the function calls (fetch, database client, Date, timers, other modules): [DEPENDENCIES]
Existing test style to follow: [TEST_STYLE]
## Instructions
1. Identify parameters, return values, thrown errors and side effects.
2. Write tests for the happy path, boundary values (empty, zero, minimum, maximum), invalid inputs and error paths.
3. Assert what JavaScript actually does. For example, `add('a', 2)` returns the string `'a2'`; it does not throw. If [SPEC] says it should throw, write the test as a failing expectation of the specification and say the code needs a change.
4. Never call real network services or databases. Mock `fetch` with `jest.spyOn(global, 'fetch')` or the project's mocking approach, mock modules with `jest.mock`, and control time with fake timers.
5. For async code, `await` every assertion (`await expect(...).resolves/rejects`) and include a rejected-promise case.
6. Match [JEST_SETUP]: use `require` or `import` consistently with the project; if it uses native ESM, note that Jest's ESM support is experimental and module mocking differs.
7. Restore mocks after each test.
## Return
1. The test file at a path that follows [TEST_STYLE].
2. A table of cases: input or setup, expected result, reason.
3. Any mismatch between [SPEC] and the code that the tests expose.
4. The command to run the tests.
## Acceptance checks
- No test depends on the network, the real clock or execution order.
- Every async test awaits its assertions.
- Expected values match JavaScript semantics for the given code.
- Results are not reported as passing unless the tests were run.Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Code (src/fetchUser.js, CommonJS):
async function fetchUser(id) {
if (!Number.isInteger(id) || id <= 0) throw new TypeError('id must be a positive integer');
const res = await fetch(`https://api.example.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
module.exports = { fetchUser };
Spec: same as code
Jest: 30, testEnvironment node, no transform, CommonJS
Dependencies: global fetch (Node 22)
Style: tests in __tests__/name.test.js__tests__/fetchUser.test.js using require, jest.spyOn(global, 'fetch') with mockResolvedValue objects for ok: true (returning a user) and ok: false with status 404, cases for id 0, -1, 1.5 and '1' expecting TypeError via await expect(...).rejects.toThrow(TypeError), a network rejection case, an assertion that fetch was called with the exact URL for id 42, and afterEach(() => jest.restoreAllMocks()). Illustrative expectation, not a recorded model run. The original page's add('a', 2) expectation was checked locally in Node: it returns 'a2' rather than throwing (see report).Ask questions or share concrete improvements.
No comments yet.
Sign in to join the discussion.
Guides for adapting and checking prompts: