How to use fetch mocking and msw together #2421
-
|
I'm currently using msw well, but I don't have a clue what to do about certain jest taunts. So I'm looking for help. const someData = jest.fn();
jest.spyOn(window, "fetch").mockImplementation(url => {
switch(url) {
case: "someUrl":
return someData();
default: wantMsw; // <- I'd like to work on this part to msw
}
});
...
expect(someData).toHaveBeenCalledTimes(1);I'm originally using msw, so i don't have to mock fetch However, since there is no need to mock all api, I would like to delegate the task to the handler of msw again in the default value of switch Will it be possible ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Hi, @wslp12. Here's what I suggest.
test('your test', () => {
let requestCallCount = 0
server.use(
http.get('/some-url', () => {
requestCallCount++
// ...handle or passthrough this request.
})
)
})You can return nothing from a request handler. In that case, MSW will try to look up another matching handler for the same request. If it finds none, the request will be performed as-is. That is likely not what you want in tests because you always want to mock the network and focus on what your network-dependent logic is doing (like counting request calls above). Please also see Execution order for request handlers. That might help. |
Beta Was this translation helpful? Give feedback.
Hi, @wslp12. Here's what I suggest.
You can return nothing from a request handler. In that case, MSW will try to look up another matching handler for the same request. If it finds none, the request will be performed as-is. That is likely not what you want in tests because you always want to mock the network and focus on what your network-dependent logic is doing (like counting request calls…