DEV Community

Discussion on: The basic form for React component mocks

Collapse
 
vishal1419 profile image
Vishal Sherathiya • Edited

When using jest.mock with React + Typescript, first test case fails because render method gets an object instead of component.


Solution:

The component in the example is using named Export, but my component was using Default Export.

So, I tried this code:

jest.mock('../../components/Table', () => ({
  default: jest.fn(() => <div data-testid="Table" />),
}));
Enter fullscreen mode Exit fullscreen mode

But still I was getting an error, so I used this code:

jest.mock('../../components/Table', () => ({
  __esModule: true,
  default: jest.fn(() => <div data-testid="Table" />),
}));
Enter fullscreen mode Exit fullscreen mode

After that I also had to downgrade react-scripts to 3.4.0 and add a new package:

npm i -D jest-environment-jsdom-sixteen
Enter fullscreen mode Exit fullscreen mode

And last change was to use the newly installed library in package.json. Please see new environment added to scripts:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom-sixteen",
    "eject": "react-scripts eject"
},
Enter fullscreen mode Exit fullscreen mode

After doing this hard work, everything is working fine now.


Side Effects:

In VS Code, Files explorer marks test files red.
Also, tests not showing icon of success or failure in coding area.
But no issues when running the test cases.

Solution to that is preety easy.
Either restart VS Code
Or restart Jest Runner and all the side-effects will be removed.


Credits:

github.com/facebook/jest/issues/97... - suggestions on changing packages
thoughtbot.com/blog/mocking-react-... - __esModule: true comes from this post.

Collapse
 
hanvyj profile image
hanvyj

Cannot get this solution to work.

 Error: Uncaught [Error: mockConstructor(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.]
Enter fullscreen mode Exit fullscreen mode

Downgraded react-scripts to 3.4.0, installed jest-environment-jsdom-sixteen, running react-scripts test --env=jsdom-sixteen, just can't get it to run.

Collapse
 
hanvyj profile image
hanvyj • Edited

Finally! I had:

beforeEach(() => {
  jest.resetAllMocks();
});
Enter fullscreen mode Exit fullscreen mode

Which if course, was resetting the implementation. I think the issue is react-scripts 4 added "resetMocks": true, as a default so it might be fixed by just:

  "jest": {
    "resetMocks": false,
  }
Enter fullscreen mode Exit fullscreen mode

in your package.json