Does Jest AutoMocking work when testing React components?
Asked Answered
I

1

7

My limited number of tests seem to suggest that the answer is no. I'm writing a unit test for a parent level React component (aka a controller view) that has a dependency on a store. However, Jest is not providing an auto-mock for the store, as the documentation suggests it should, and is instead calling the real implementation.

Is this a bug or by design? If the latter, is the takeaway that unit testing react components is not desirable?

Edit 1

Automocking works just fine when testing a CommonJs module; it's just not working for react components.

Indented answered 12/3, 2015 at 4:7 Comment(7)
Did you by any change turn the automock feature off?Diadem
No, but to be sure I explicitly turned it on via jest.autoMockOn() to no avail.Indented
@MitchA any luck on this one? I'm running into the same thing. Even with jest.autoMockOn() it isn't actually mocking anything.Anvil
No updates I'm afriad. Automocking only works when testing non React components.Indented
Are you using coffee script? Jest has an issue where calling jest.dontmock causes it to not mock any coffee script files. If this is the case, You can use jest.requireActual insteadRokach
I have Jest auto mocking components in my app without needing to do anything special. Anyway you could share some code to get a better idea of what might be going on?Riba
Can you provide a limited test case? e.g. including the store and how you are requiring it? I haven't been able to replicate this in my limited testing.Catholicity
D
0

Sounds like your test is an Integration Test instead of a Unit Test. Jest mocks everything because it is used primarily for Unit Tests. I share with you the pattern that has helped me to simplify and speed up my unit testing.

Extract helper methods

Extract methods that perform logic eg. mapping, filtering, etc. to a Utils module in a different file. Then test the Utils module instead of the React component. That way you reduce the complexity of testing.

The same applies for stores... Try to run all the logic in Utils modules. Leaving Stores with own methods just for getters and setters.

Don't forget to unMock the keyMirror and Dispatcher

When managing constants using KeyMirror, its very easy to forget to unMock this module. Stores normally use a lot of constants for the ActionTypes.

The same goes for the Dispatcher dependencies and the EventEmitter.

Dustheap answered 17/5, 2015 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.