Front End Testing - SE701Group2/daily-focus GitHub Wiki
As mentioned on the Environment Setup page, you need to use npm version 6. Run npm install -g [email protected]
Test files must be named like: MyComponent.test.js
npm test .
will run all tests. Running npm test --watch
will allow any updated test to run on save.
- Jest
- Jest-Dom v^5.11.9
-
Enzyme v^3.11.0
- Enzyme Adapter React 16 v^1.15.6
- react-test-renderer v^16.14.0
Snapshot testing is used for React Components. See here for info on how and why to use snapshot testing.
react-test-renderer
library is used. (Note, Enzyme is not used due to a version incompatibility with Jest causing the generated snapshots to be broken. See here.)
For example:
import React from "react";
import ShallowRenderer from "react-test-renderer/shallow";
import Header from ".";
test("it renders correctly", () => {
const shallowRenderer = new ShallowRenderer();
const snapshotComponent = shallowRenderer.render(<Header />);
expect(snapshotComponent).toMatchSnapshot();
});
When this test is run for the first time, a snapshot will be generated in a __snapshots__
folder. This folder should be committed. Pressing u
in --watch
mode will regenerate a failing snapshot. This should only be done if the changes are intentional.
enzyme
is used for other unit tests to verify intended functionality:
For example:
import React from "react";
import SelectWidgetsModal from ".";
import { shallow } from "enzyme";
import Dialog from "@material-ui/core/Dialog";
import Button from "@material-ui/core/Button";
test("Button opens modal when clicked", () => {
const wrapper = shallow(<SelectWidgetsModal />);
expect(wrapper.find(Dialog).prop("open")).toBe(false);
wrapper.find(Button).simulate("click");
expect(wrapper.find(Dialog).prop("open")).toBe(true);
});