Toni Chaz
Toni Chaz

Reputation: 731

React Jest to match snapshot, crash when testing component with child components

I have some components with child components from third parties addons/libraries. I use Jest for my unit test and toMatchSnapshot() method. I tried to exclude the child components with jest.unmock('ChildComponet.js') and i get this error:

jest.unmock('ChildComponet.js') was called but automocking is disabled. Remove the unnecessary call to jest.unmock or enable automocking for this test via jest.enableAutomock();. This warning is likely a result of a default configuration change in Jest 15.

I enabled jest.enableAutomock(); and now i have tis error:

TypeError: Cannot read property 'DEFINE_MANY' of undefined

I put this on my package.json but nothing happens:

"unmockedModulePathPatterns": ["rootDir/node_modules/react"]

Any ideas?

is the correct way to make unit test of components in React?

Upvotes: 0

Views: 2421

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110892

The easiest way to mock out react components I found so far is to use:

jest.mock('component', ()=> 'ComponentName')

before you the import statement of the module you want to test.

The first parameter is either the name of global npm module or the path to your local component (note that the path in relative to your test file). The second parameter is just a function that returns a string (I always return the same name I use in jsx). This will result in a dump component that does nothing but have the same name as your original component. So in your snapshot you will see no difference, beside the mocked component will not render any childs.

Now to the error messages you got.

jest.unmock('ChildComponet.js') was called but automocking is disabled...

The problem is that you use jest.unmock instead of jest.mock. Jest has the feature to automatically mock all the dependencies of your modules. With auto mock enabled you could use jest.unmock to get the real implantation for some essential libs like lodash or moment. As the auto mock feature was confusing for a lot of people, they decide to make it optional. Tldr you tried to un mock something that was not mocked in the first place as you don't enabled auto mocking.

TypeError: Cannot read property 'DEFINE_MANY' of undefined

When you enable auto mocking every imported module is replaced with undefined. I cant say much about the unmockedModulePathPatterns setting but I believe you have to use the same pattern you use to import the module, so if it is a global you don't have to put the path to the node_modules folder in it.

Upvotes: 1

Related Questions