import {MockAgent, setGlobalDispatcher} from 'undici';
process.env.BASE_API = 'http://localhost';
const mockAgent = new MockAgent();
setGlobalDispatcher(mockAgent);
// MockPool
const mockHttpClient = mockAgent.get('http://localhost');
// Then later i call in my jest on top
mockHttpClient
.intercept({
path: '/api/v3/ui/searchTags',
method: 'GET',
headers: {
accept:
MAP_SMART_SEARCH_CONTENT_TYPE.listAllTagsQuery.willSendAccept,
},
})
.reply(200, JSON.stringify({data: res.allTags}));
So after digging a bit with undici library, I found that they use a mock agent which can intercept the requset. I applied the following in my testing setupTest.ts.
import {MockAgent, setGlobalDispatcher} from 'undici';
const mockAgent = new MockAgent({connections: 1});
setGlobalDispatcher(mockAgent);
[...]
export {mockAgent}
The mock works only when using request client from undici. So the only intersepcted request was the one called using the module not the one from the class context this.METHOD.
I'm trying to mock the response by intercepting
undici
request but with no success!I've implemented the data source and it works fine with real testing. But we are trying to intercept HTTP request with jest for testing purposes.
The following mock configuration found here https://github.com/nodejs/undici/blob/main/docs/api/MockPool.md
Not sure what is missing? I tried also
msw
but seems they don't supportundici
yet https://github.com/mswjs/interceptors/issues/159UPDATE:
So after digging a bit with
undici
library, I found that they use a mock agent which can intercept the requset. I applied the following in my testingsetupTest.ts
.And in my test code
The mock works only when using
request
client fromundici
. So the only intersepcted request was the one called using the module not the one from the class contextthis.METHOD
.Seems something wrong with wiring request but not sure what is the issue exatly!
Any idea of how to intercept the request? Thanks in advance.