breaking change in 21.7.0 when mocking fetch
Version
21.7.0
Platform
Darwin Stevens-MacBook-Pro.local 23.2.0 Darwin Kernel Version 23.2.0: Wed Nov 15 21:54:55 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T8122 arm64
Subsystem
No response
What steps will reproduce the bug?
- Make a test which mocks fetch:
import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import { fetchSomething } from '../lib/index.mjs'; describe('my test suite', () => { it('fetch stuff', async (t) => { const mockValue = { key: 'value' }; const mockFetch = async () => ({ json: async () => mockValue, status: 200, }); t.mock.method(global, 'fetch', mockFetch); assert.deepStrictEqual(await fetchSomething(), mockValue); t.mock.restoreAll(); }); });
which produces:
✖ fetch stuff (0.894292ms) TypeError [ERR_INVALID_ARG_VALUE]: The argument 'methodName' must be a method. Received undefined at MockTracker.method (node:internal/test_runner/mock/mock:241:13) at TestContext.<anonymous> (my.test.mjs:13:12) at Test.runInAsyncScope (node:async_hooks:206:9) at Test.run (node:internal/test_runner/test:641:25) at Suite.processPendingSubtests (node:internal/test_runner/test:382:18) at Test.postRun (node:internal/test_runner/test:732:19) at Test.run (node:internal/test_runner/test:690:12) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:966:7) at async startSubtest (node:internal/test_runner/harness:218:3) { code: 'ERR_INVALID_ARG_VALUE' }
to fix the break, i have to reference global.fetch before mocking it...ie:
fetch; t.mock.method(global, 'fetch', mockFetch);
How often does it reproduce? Is there a required condition?
Consistently
What is the expected behavior? Why is that the expected behavior?
Should not break existing code on a minor or patch semver change of node.
What do you see instead?
It breaks
Additional information
This is the PR which introduced the break: #51598 (comment)