MSW 2: Mock interdependent requests #2066
-
Hi, looking at a way to mock responses for interdependent requests. Test case and current implementation in Nock it('should iterate over all pages to gather resources', async () => {
nockCF
.get('/v2/test')
.reply(200, '{"next_url":"/v2/test?page=2","resources":["a"]}')
.get('/v2/test?page=2')
.reply(200, '{"next_url":null,"resources":["b"]}');
const client = new CloudFoundryClient(config);
const response = await client.request('get', '/v2/test');
const collection = await client.allResources(response);
expect([...collection].length).toEqual(2);
expect(collection[1]).toEqual('b');
}); where public async allResources(response: AxiosResponse): Promise<any> {
const data = response.data.resources;
if (!response.data.next_url) {
return data;
}
const newResponse = await this.request('get', response.data.next_url);
const newData = await this.allResources(newResponse);
return [...data, ...newData];
} I've attempted to mock both requests in MSW as normal, but test just hangs (and ultimately errors with JS Heap error) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi, @kr8n3r. Since you want to mock responses to those requests (which is implied by the Nock example you posted), neither Here's that Nock example written using MSW request handlers: import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
const server = setupServer(...happyPathHandlers)
// Don't forget to start and close the server
// in the beforeAll/afterAll hooks!
it('should iterate over all pages to gather resources', async () => {
server.use(
http.get('/v2/test', () => {
return HttpResponse.json({ next_url: '/v2/test?page=2', resources: ['a'] })
}),
http.get('/v2/test?page=2', () => {
return HttpResponse.json({ next_url: null, resources: ['b'] })
})
)
const client = new CloudFoundryClient(config);
const response = await client.request('get', '/v2/test');
const collection = await client.allResources(response);
expect([...collection].length).toEqual(2);
expect(collection[1]).toEqual('b');
}); If your test hangs with this network description, try following this guide. Some useful materials: |
Beta Was this translation helpful? Give feedback.
Hi, @kr8n3r.
Since you want to mock responses to those requests (which is implied by the Nock example you posted), neither
passthrough()
norbypass()
should be used. Those APIs are for letting MSW ignore the request completely (passthrough) or perform the intercepted request as-is without causing it to go through the handler again, causing an infinite loop (bypass).Here's that Nock example written using MSW request handlers: