Hey there! I have a module that exports some methods and I want to test them with unit tests. My project is built on typescript ^3.9.7 and has jest ^26.1.0 and ts-jest ^26.2.0 installed.
One of the methods in question requires node-fetch ^2.6.0 to utilize window.fetch in a node environment.
import fetch from 'node-fetch'
export const fetchResponseFromRemoteFile = (
remoteFileUrl: string
): Promise<Response> =>
fetch(remoteFileUrl)
.then(res => {
return res.status === 200
? res
: new Error(`failed to retrieve ${remoteFileUrl}`)
})
.catch(e => e)
In one of my tests, I aim to verify that fetchResponseFromRemoteFile invokes fetch.
Approach 1
import { mocked } from 'ts-jest/utils'
import fetch from 'node-fetch'
jest.mock('node-fetch')
it('fetches', async () => {
const expectedResponse = { a: 1 }
mocked(fetch).mockImplementation( () => <any>expectedResponse)
...
})
// mocked(fetch).mockImplementation( () => <any>expectedResponse)
TypeError: (0 , _utils2.mocked)(...).mockImplementation is not a function
Approach 2
it('fetches', async () => {
const expectedResponse = { a: 1 }
;(fetch as jest.Mock).mockReturnValue(Promise.resolve(new Response(expectedResponse)))
const remoteFile = await utils.fetchResponseFromRemoteFile(mockUrl)
expect(fetch).toHaveBeenCalledTimes(1)
expect(remoteFile.status).toEqual(200);
expect(remoteFile.body).toEqual(expectedResponse);
...
})
// ;(fetch as jest.Mock).mockReturnValue(Promise.resolve(new Response(expectedResponse)))
ReferenceError: Response is not defined
Approach 3
import fetch from 'node-fetch'
jest.mock('node-fetch', () => jest.fn())
it('fetches', async () => {
const expectedResponse = { body: { a: 1 } }
const response = Promise.resolve(expectedResponse)
fetch.mockImplementation(()=> response)
...
})
// fetch.mockImplementation(()=> response)
TypeError: _nodeFetch.default.mockImplementation is not a function
Any ideas on what could be causing these issues?
Thanks in advance!