Testing React is an interesting endeavor. Since it is almost entirely UI (User Interface) specific you shouldn't need to test everything. At least with regards to Unit Tests. When it does come down to testing there seems to be quite a bit of confusion as to how to test.
Recently I have been working with a React codebase and have been attempting to write tests as these were almost completely absent. This has proven more difficult than most testing I do these days. I believe this is due to the fast based development of Javascript frameworks. Generally I am developing in Java, Python or PHP. These have fairly muture test frameworks.
Since the codebase I have been working on is using Jest and Enzyme I decided to go with that. The two primary methods of testing the codebase I have come across is shallow and mount. Shallow as the name suggests doesn't drill into the dependancies, whereas mount does the opposite. The preferable option is to use shallow, however a gotcha with this is the props. Since these don't appear to be in the scope of the class being called you have to mock these, otherwise you will not be able to testing anything that requires the props. You can mock props as follows:
describe('When MyPage is rendered with data', () => {
const profilePage = shallow(<MyComponent
myprop1={10}
myprop2={20} />);
test('whatever I want to test', () => {
expect(profilePage.prop('myprop1')).toEqual(10);
expect(profilePage.prop('myprop2')).toEqual(20);
});
});
The challenge I found in building tests is that my IDE kept getting confused as to what testing library I was using. One technique I use when doing exploritory testing is to set break points throughout the code that can both tell me where the testing is reaching but also I can see what the data structures look like. Especially in dynamically typed language. I found this technique was very hit and miss in react.
The other challenge I found is some tests will pass no matter what your testing. This is far from a good thing as you want to highlight any fagility in your codebase, and if your tests will pass when the app cannot even compile you will loose all faith in your testing framework.
Anyway I hope this helps anyone trying to write unit tests for React.
Copyright © 2020 | Ben Hutton