The user Dashboard of TripTime will show a loading state to the user while it is fetching data from the API, and display cards of the trips once the loading have been completed. Here’s what it looks like:
Now here’s the problem: how do I test that the UI is working properly at these two different stages? Luckily, we can call setState on the instance rendered by the React Test Renderer.
Here’s what I did for dashboard that is at the loading state:
test('Check if Dashboard displays TripCards when it is loaded', () => { userHomePageRenderer.root.instance.setState({ currentLoading: false, pastLoading: false, planningLoading: false, }) expect(userHomePageRenderer.root.findAllByType(TripCard).length).toBe(12) expect(userHomePageRenderer.toJSON()).toMatchSnapshot() })
Unluckily, Jest does not support having multiple SnapShots for the same test suit yet. which is why these two states are tested in two separate test files, and generates src/spa/__tests__/components/homepage/__snapshots__/DashboardLoaded.test.js.snap and src/spa/__tests__/components/homepage/__snapshots__/DashboardLoading.test.js.snap respectively.
Another thing worth noting is that import axios from 'axios'; did not import the node modules, but imports src/spa/__mocks__/axios.js:
1 2 3 4 5 6 7
/** src/spa/__mocks__/axios.js */
const mockAxios = jest.genMockFromModule('axios')
mockAxios.create = jest.fn(() => mockAxios)
exportdefault mockAxios
This mocks axios so that we can conduct axios.get.mockResolvedValue({ data: [] });.