I am new to typescript and apologize in advance if this is trivial. I have a function that uses Fetch internally like so
export class MyClass {
classVar1: string;
classVar2: string;
...
async postEvent(event: eventSchema) {
const headers = {
'Content-type': 'application/json',
'Api-Key': 'APIKEY}',
};
let result = null;
const response = await fetch('url', {
method: 'POST',
body: event,
headers: headers,
});
result = await response;
return result;
}
}
I am trying to test the postEvent method and for that I am trying to mock the fetch portion ONLY. But no matter how I approach this, still the actual method is the one that gets called. Based on what I found online, this is what I have in my .spec.ts file
import { MyClass } from './my-class';
import fetch from 'node-fetch';
jest.mock('node-fetch');
describe('My class mocked fetch', () => {
beforeEach(() => {
(MyClass as any).postEvent = jest.fn();
(fetch as any) = jest.fn().mockResolvedValue({
url: 'url',
status: 200,
statusText: 'OK',
counter: 0,
});
});
it('Calls mockedFetch and gets the mocked values', async () => {
expect(fetch).toHaveBeenCalledTimes(0);
const response = await myClass.postEvent('testMsg')
console.log('RESPONSE', response)
});
In the last line (console.log('RESPONSE', response)), I expect to see the mockResolved values, i.e
url: 'url',
status: 200,
statusText: 'OK',
counter: 0,
Yet it returns whatever the actual fetch would generate.
Can anyone help with this?
p.s I have also read about the spyOn approach, yet I am not able to find an example for typescript that would fit my use case above. There is an example for JS like this
const fetchMock = jest.spyOn(global, 'fetch').mockImplementation(() => Promise.resolve({ json: () => Promise.resolve([]) }))
But it throws an exception if used in type script like below
'Promise<{ json: () => Promise<any[]>; }>' is not assignable to type 'Promise<Response>'.