Jest中的Snapshot快照测试

当我们在写业务代码或者配置文件的测试用例时,可能会牵扯到不断修改的过程。那么就会面临着一个比较麻烦的问题:就是每次修改业务代码时,都要相对应的修改测试用例中的断言代码。那么如何避免这个问题呢?使用Snapshot快照即可解决这个大麻烦!

Snapshot快照的作用就是:把每次修改后的代码形成快照,与上次代码生成的快照做对比,若有修改部分,则会出现异常快照提示。

普通的Snapshot (toMatchSnapshot)

demo

业务代码:demo.js

export const generateConfig = () => {
  return {
    server: 'http://localhost',
    port: 8080,
    domain: 'localhost'
  }
}

测试代码:demo.test.js

import { generateConfig } from './demo'

test('测试 generateConfig ', () => {
  // 1.普通匹配,每次修改配置时,都需要修改测试用例代码
  // expect(generateConfig()).toEqual({
  //   server: 'http://localhost',
  //   port: 8080,
  //   domain: 'localhost'
  // })  
  // 2.使用快照匹配
  expect(generateConfig()).toMatchSnapshot()
})

toMatchSnapshot()快照匹配的执行流程:

  • 第一次运行generateConfig函数时,没有快照,调用toMatchSnapshot()匹配器时,会自动帮我们生成一个快照。把generateConfig函数返回的内容存到快照里边去。
  • 当我们修改业务文件进行保存后,toMatchSnapshot()又会生成一次快照,跟上次生成的快照相对比,如果一致,则测试通过,如果不一致,则测试不通过,证明有代码改动。
  • 快照文件为:_ _ snapshots_ _/demo.test.js.snap (如下)

修改业务代码:demo.js(新增time配置项)

export const generateConfig = () => {
  return {
    server: 'http://localhost',
    port: 8080,
    domain: 'localhost',
    time: '2019'
  }
}

当修改业务代码后,测试用例将生成新的快照和上次快照内容做对比,对比结果不一致,则测试无法通过:

同时能提示我们,是否真的要改测试文件。如果想以修改后的配置文件为准,则可在命令行执行 ‘w’ 命令,进入jest命令模式,然后执行 'u’命令来更新不通过的快照。

行内的Snapshot (toMatchInlineSnapshot)

使用行内Snapshot的前提是:安装 prettier

npm  i  prettier  -D
demo

业务代码:demo.js

export const generateAnotherConfig = () => {
  return {
    server: 'http://localhost',
    port: 8080,
    domain: 'localhost',
    time: new Date()
  }
}

测试代码:demo.test.js

import { generateAnotherConfig } from './demo'

test('测试 generateAnotherConfig ', () => {
  expect(generateAnotherConfig()).toMatchInlineSnapshot({
    time: expect.any(Date) 
  }) 
})

执行测试:npm test 即生成行内快照 (如下)

=> 行内Snapshot和普通Snapshot的区别
  • toMatchInlineSnapshot() 行内Snapshot把生成的快照放到了测试用例里边,作为第二个参数的形式传入。
  • toMatchSnapshot() 普通Snapshot会把生成的快照放到单独的文件里。
=> 更新、跳过快照

首先,按 ‘w’ 进入jest命令模式。

  • 按 ‘u’ 更新快照
  • 按 ‘s’ 跳过快照
  • 如果有多个Snapshot发生冲突时,要进入 ‘i’ 交互模式,一次一次的去确认每个Snapshot的变量,确认没问题之后,然后分别按 ‘u’ 进行每个快照的更新。
=> 动态匹配 expect.any

注: 当我们的业务代码是动态改变的时候,那么每次生成的测试快照都是不同的,就会导致我们的测试用例每次都无法通过,我们可以通过在匹配器里做数据的类型限制,进行快照测试。例如:
业务代码:demo.js

export const generateConfig = () => {
  return {
    server: 'http://localhost',
    port: 8080,
    domain: 'localhost',
    time: new Date() // 取当前时间
  }
}

测试代码:demo.test.js

import { generateConfig } from './demo'

test('测试 generateConfig ', () => {
  expect(generateConfig()).toMatchSnapshot({
    time: expect.any(Date)  // 限制数据类型,也可为Number/String/Object等
  })
})

在匹配器中使用expect.any做数据的类型限制后,当再次生成测试快照时,只要这次的time是Date类型,即可通过测试。

发布了54 篇原创文章 · 获赞 22 · 访问量 7227

猜你喜欢

转载自blog.csdn.net/Riona_cheng/article/details/102408962
今日推荐