I've recently starting programming. I'm on a team who is programming in React and is using Enzyme, Mocha and Chai for unit testing. See package versions below.
When testing a component where there are several use cases that require different prop values, should I use beforeEach() and then setProps() in each test, or should I do an explicit mount() (or shallow()) at the start of each test? Does it matter?
For example, I could use beforeEach() to mount without any props and then use setProps() in each test like this (using pseudocode):
describe('MyComponent', () => {
beforeEach(... let component = mount(<MyComponent />) ...)
it('tests use case 1', () => {
// set prop A = 123
component.setProps({A: 123})
// assert some stuff
})
it('tests use case 2, () => {
// set prop A = 456 and B = 'foo'
component.setProps({A: 456})
component.setProps({B: 'foo'})
// assert some stuff
})
})
or I could do a use-case specific mount at the start of each test, passing in props in the mount, like this:
describe('MyComponent', () => {
it('tests use case 1', () => {
...mount(<MyComponent A=123 />)
// assert some stuff
})
it('tests use case 2, () => {
...mount(<MyComponent A=456 B='foo' />)
// assert some stuff
})
})
What are the pros and cons of each method? Is there a best practice?
Packages
- "enzyme": "^3.3.0",
- "enzyme-adapter-react-16": "^1.1.1",
- "mocha": "^5.0.0",
- "chai": "3.5.0"
setProps
it will execute the update life cycle of the component, it's not same as passing the props initially. So when you want to test the componentDidMount/useEffect with some dependency, you won't be able to do with setProps. I personally prefer the 2nd approach with a factory method as it's cleaner and everything that the other reader needs to understand is at one place. Here is a nice article by Kent.C.Dodds on such patterns. kentcdodds.com/blog/test-isolation-with-react – Hardik Modha