'How to test if request has been executed with specific parametrs
I'm trying to mock node-fetch and test which headers and method were passed to it.
Code that i'm trying to test
export default class Client {
baseUrl = 'https://sample.com';
headers = {
'Content-Type': 'application/json'
};
async request({ endpoint, params, method = 'GET' }) {
const url = new URL(`${this.baseUrl}/${endpoint}`);
if (method === 'GET' && params) {
url.search = new URLSearchParams(params);
}
const response = await fetch(url, {
method,
headers: this.headers,
...(method !== 'GET' ? { body: JSON.stringify(params) } : {})
});
return response.json();
}
}
My test file
global.fetch = jest.fn(() =>
Promise.resolve({
json: async () => ({ status: 200 })
})
);
const client = new Client();
it('tests client', async () => {
const meta = {
'Content-Type': 'application/json'
};
const headers = new Headers(meta);
const req = { headers: meta, method: 'GET' };
const reqGet = await client.request({ endpoint: 'api/v2' });
expect(reqGet.status).toBe(200);
expect(fetch).toHaveBeenCalledWith(`${client.baseUrl}/api/v2`, {
method: 'GET',
headers: meta
});
});
The problem begins when I pass an object to toHaveBeenCalledWith it seems like it ignores it and only shows that expected baseUrl without any parameters.
My second try was to pass objects like so
expect(fetch).toHaveBeenCalledWith(
`${client.baseUrl}/api/v2`,
expect.objectContaining({
method: 'GET',
headers: meta
})
);
And this is the output from a jest
Expected: "https://sample.com/api/v2", ObjectContaining {"headers": {"Content-Type": "application/json"}, "method": "GET"}
Received: "https://sample.com/api/v2", {"headers": {"Content-Type": "application/json"}, "method": "GET"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
