Marnie A.
Marnie A.

Reputation: 73

Should I verify that props were set after component mounts in my unit tests? (using Enzyme, Mocha, Chai)

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.

My team insists that the unit test file for each component should have the following test:

beforeEach(() => {
   component = mount(<MyComponent />)
})

it('renders with correct properties', () => {
   component.setProps({
     height: 100,
     width: 500,
     placeholder: 'Some value here'
   })
   expect(component.prop('height')).to.equal(100)
   expect(component.prop('width')).to.equal(500)
   expect(component.prop('placeholder')).to.equal('Some value here')
})

That's the end of the test. To me, this test looks like it's just testing that React sets the props. I feel we can trust what React is doing and instead should be testing how we use React to render our component. I'd rather test the affects of the prop values on other props, state, and how the component renders as a result of the props.

But I'm new and my team thinks I'm wrong in my concern, so I thought I'd check around: Is there value in the above test case that I'm missing? Is it good practice?

Related Questions

Packages

Upvotes: 2

Views: 372

Answers (1)

caladeve
caladeve

Reputation: 496

Completely agree - it is pointless to test the behavior of the React library itself. In my team we use Jest's snapshot testing as an initial basic test to check the render and then we do a lot of state-transition testing on top of that; this may help you here because it seems like you're looking for a bit of a "sanity check that it renders in it's basic expected output before we check anything else yet" kind of test. So we'll do the same mount as you have stated and then our expectation is:

expect(toJson(component)).toMatchSnapshot();

By doing toJson you can at least read the output of the snapshot in a more human-readable form compared to not doing toJson.

There are pros and cons to incorporating snapshot testing to your project - some people say it's overkill and some people find it useful. Personally I find it useful to see if any code that I add in future breaks existing renders, making my unit tests actually useful and relying less on manual testing. Have a read of this thread which talks more about snapshot testing.

Upvotes: 1

Related Questions