question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Jest - Request sometimes not intercepted

See original GitHub issue

Environment

Name Version
msw 0.26.2
node 12.19.1
OS macOS Big Sur 11.2

Request handlers

import '@testing-library/jest-dom/extend-expect';
import { render, screen, waitFor } from '@testing-library/react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import React from 'react';
import { Provider } from 'react-redux';
import { MemoryRouter, Route } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import Test from '..';

const mockResponse: any = {
    // ...
};

const server = setupServer(
    rest.get(`...`, (_req, res, ctx) => {
        return res(ctx.json(mockResponse));
    }),
    )
;

describe('Test', () => {
    beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
    beforeEach(() => {
        render(<Test />, { wrapper });
    });
    afterEach(() => server.resetHandlers());
    afterAll(() => server.close());

    const mockStore = configureStore([]);
    const store = mockStore({});

    const wrapper: React.FC = ({ children }) => (
        <MemoryRouter initialEntries={['foo/1']}>
            <Provider store={store}>
                <Route path='foo/:id'>{children}</Route>
            </Provider>
        </MemoryRouter>
    );
    
    // ...

    it('...', async () => {
        await waitFor(() => screen.getByTestId('..'));
        expect(screen.queryByTestId('...')).toBeNull();
    });
});

Actual request

// ../Test.tsx

// ...
useEffect(() => {
        if (params.id) {
            axios.request(axiosRequestArgs);
                .then((res) => setResponse(res.data))
                .catch(() => {
                    /*...*/
                })
                .finally(() => {/*...*/);
        }
    }, [params.id]);
// ...

Current behavior

The vast majority of the time everything works perfectly. Every once in a while we get the following error in our CI builds:

FAIL src/.../__test__/Test.test.tsx
--
257 | ● Test › ...
258 |  
259 | Network Error
260 |  
261 | at createError (node_modules/axios/lib/core/createError.js:16:15)
262 | at XMLHttpRequest.handleError (node_modules/axios/lib/adapters/xhr.js:84:14)
263 | at XMLHttpRequest.<anonymous> (node_modules/jsdom/lib/jsdom/living/helpers/create-event-accessor.js:32:32)
264 | at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:318:25)
265 | at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
266 | at XMLHttpRequestImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
267 | at fireAnEvent (node_modules/jsdom/lib/jsdom/living/helpers/events.js:18:36)
268 | at requestErrorSteps (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:128:3)
269 | at dispatchError (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:59:3)
270 | at Object.validCORSHeaders (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:74:5)
271 | at receiveResponse (node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:796:19)
272 | at Request.<anonymous> (node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:657:36)
273 | at Request.onRequestResponse (node_modules/request/request.js:1059:10)

It seems like the request isn’t actually being intercepted. This is the same stacktrace I get if I never actually call server.listen and its complaining about bad CORS headers. I’m wondering if there is a possibility of some race condition where the test is run before requests can be intercepted, even though server.listen should be synchronous. Either that or I’m missing something obvious (very likely)

Expected behavior

This error to never occur

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:4
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
alettiericommented, Mar 18, 2021

I was going to follow up on this. I actually agree, at least in my instance I think it’s a race condition issue with the way the unit test is setup, not the library. Using the DEBUG flag was pretty helpful in allowing me to troubleshoot.

2reactions
alettiericommented, Mar 8, 2021

I’ll work on a solution, here and here

Read more comments on GitHub >

github_iconTop Results From Across the Web

nock is not intercepting my request - node.js - Stack Overflow
This is an old question but I believe the answer is that you need to set the axios http adapter: import axios from...
Read more >
nock - Devpost
It will intercept an HTTP GET request to '/users/1' and reply with a status 200, and the body will contain a user representation...
Read more >
Mock Service Worker adopts a brand-new request interception ...
Extending the ClientRequest class means that all requests begin to establish actual HTTP connection. This quickly becomes problematic. When you' ...
Read more >
Debugging uncaught requests - Recipes - Mock Service Worker
Whenever you are faced with a request that is not being intercepted, follow the suggestions on this page to debug the issue.
Read more >
A Comprehensive Guide to Mock Service Worker (MSW)
Mock Service Worker intercepts real network requests that your tests ... to set up and configure Jest, and this blog post will not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found