knee-cola/jest-mock-axios

axios.CancelToken.source() returns `undefined`

Chris-Thompson-bnsf opened this issue · 7 comments

jest-mock-axios version: 4.2.1
jest version: 26.6.0

Upgrading an existing React project by several versions, including going from Jest 24.x to Jest 26.x, and a ton of our tests which were mocking Axios are now failing with this error.

Minimal repro:

import axios from 'axios';

jest.mock('axios'); 

it('should not throw when getting a cancel token', () => {
	//arrange
	var cancelToken = axios.CancelToken;

	//act
	const source = cancelToken.source();

	//assert
	expect(source).toBeDefined();
	const token = source.token;
	expect(token).toBeDefined();
});

I have seen similar issues which were closed, such as this one, but I believe the minimal repro above is following the suggested pattern and the test is still failing on the first assert.

Hi,

thanks for reporting this bug! Unfortunately, I am unable to reproduce the bug using the provided minimal example and the latest versions of jest and this library.

Are you sure you are using this library correctly? Please note that using jest.mock('axios') shouldn't be necessary (as explained in #61). Instead place a axios.js file into __mocks__/ with the contents described in the Readme. Are other parts of this library (e.g. responding to requests) working correctly for you?

The tests which were making use of the library were working prior to the version updates that were being done. I tested with and without the jest.mock('axios') line (both in the test itself, and in the setupTests.js file), and also tested that the issue remains whether I use a axios.js or axios.ts file in the __mocks__/ directory (at the root of the repo, sibling of node_modules/).

@Chris-Thompson-bnsf Sorry for the late reply! I created a sample reproduction repo at kingjan1999/jest-mock-axios-repo-canceltoken. Can you try to reproduce the issue with this repro (yarn test)? Are there any differences between your project and the sample repro?

@kingjan1999 I was able to reproduce it with a few changes to the supplied repo. This can be seen at this fork of that repo:
https://github.com/Chris-Thompson-bnsf/jest-mock-axios-repo-canceltoken/tree/62-Repro

It required some changes to the repo in order to facilitate how react-scripts (create-react-app) works.

@Chris-Thompson-bnsf I could reproduce this with react-scripts. The issue stems from react-scripts test running with a jest config setting the project root to <rootDir>/src (the default jest config is <rootDir>). So to load the mock correctly, you need to place the __mocks__ directory under src/ (see Jest docs). This should fix the issue.

@kingjan1999 Thanks very much for the info. I was able to get past this issue with the change you outlined (moving our project's __mocks__ directory under the src directory).

I will go ahead and mark this as closed now :).

Great, glad that helped. I included that into the README.