Learning the Jest API basics
I learnt about the Jest API usage from the Jest API document. The functions that I used this time are:
describe(name, fn)
expect(value)
.toBe(value)
.not
.toEqual(value)
.toMatchSnapshot(propertyMatchers?, hint?)
Mocking webpack Modules
Jest can be used in projects that use webpack to manage assets, styles, and compilation. I did not use webpack directly, but the Next.js has built-in webpack that used to import CSS modules.
1 | // __tests__/components/homepage/TripList.test.js |
I imported css files in the TripList.js
file:
1 | import styles from '../../css/homepage.module.css'; |
But Jest does not know what to do with non-JS files at this moment, I got this error (I’ll just include the whole thing to better explain the context):
1 | Test suite failed to run |
Because this was caused by an imported module, the Using with webpack guide gave me a detailed guidance on what to do with non-js imported modules.
I used identity-obj-proxy
to mock my CSS modules, and a local fileMock.js
to define mocking of other non-JS modules:
1 | // __mocks__/fileMock.js |
I went to the jest.config.js
file, and added the moduleNameMapper
configuration.
1 | module.exports = { |
Now I could test my Next.js, and Jest knows what to do with non-JS modules.
TestRenderer
react-test-renderer
package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
React website gives clear guidance on the usage of TestRenderer.
The functions I used this time are:
TestRenderer.create()
, used to create the component renderertestRenderer.toJSON()
, used for snapshot testingtestRenderer.root
, used to get the rendered instancetestInstance.findByType()
,testInstance.findByProps()
,testInstance.findAllByType()
, used to find elements in the rendered instance
Snapshot Testing
I first heard the term snapshot testing from my TripTime teammate and it sounded quite intimidating, but it turned out to be a very handy tool for front-end testing.
The expect(value).toMatchSnapshot(propertyMatchers?, hint?)
function generates a snapshot locally when it first runs, and in the future runs will test if the new version matches the existing snapshot.
The code looks like this:
1 | describe("Test userHomepage", ()=>{ |
Next Step
What is ES6 proxy?