Preparation conditions

Build on the directories and code created in the tutorial in Section 1. If you haven’t seen the first tutorial, follow me for previous articles in this series

This tutorial focuses on how to test a snapshot in Jest. Make a copy of the code in Section 1 and addindex.jsandindex.test.jsDelete all files

Write some methods to be tested in index.js

export const data1 = (a)= > {
  return {
    name: 'Jsoning'.age: 26.time: '2020.1.1'}}export const data2 = (a)= > {
  return {
    name: 'Jsoning'.age: 26.time: new Date()}}Copy the code

Write some test instances in index.test.js

import { data1, data2 } from "./index"

it('Test snapshot data1', () => {
  expect(data1()).toMatchSnapshot({
    name: 'Jsoning'.age: 26.time: '2020.1.1'
  })
})

it('Test snapshot data3', () => {
  expect(data2()).toMatchSnapshot({
    name: 'Jsoning'.age: 26.time: expect.any(Date) // Is used to declare a time type, otherwise the time will always change, the snapshot will not pass})})Copy the code
  • toMatchSnapshotMatches the parameters to the snapshot
  • expect.any(Date)Used to match a time type

NPM run test generates a __snapshots__ folder containing the generated snapshots. When you modify the test code, it will tell you that the snapshots do not match. If you are sure you need to modify it, press u to update the snapshot. This is useful for testing UI components

If you don’t want to generate a file from the snapshot, you can

  • will__snapshots__delete
  • npm install prettier --saveInstall the prettier module on which snapshots are generated in the line
  • Write test cases inindex.test.jswrites
import { data1, data2 } from "./index"

it('Test snapshot data1', () => {
  expect(data1()).toMatchInlineSnapshot({
    name: 'Jsoning',
    age: 26,
    time: '2020.1.1'
  })
})

it('Test snapshot data3', () => {
  expect(data2()).toMatchInlineSnapshot({
    name: 'Jsoning', age: 26, time: expect. Any (Date) // used to declare a time type, otherwise the time will always change, the snapshot will not pass})})Copy the code
  • toMatchInlineSnapshotMatches the snapshot run within the linenpm run testYou can see that the snapshot is generated inside the file

That’s all. Snapshot tests are useful for testing UI components and preventing someone else in the project from accidentally modifying the file

The next tutorial will cover TDD+ unit testing, BDD+ integration testing

My ability is limited, the article may have incorrect or inappropriate parts, I hope you can point out

Pay attention to the public number, and I learn the front-end necessary skills, front-end automation test JEST