Jest 中的 snapshot 快照测试 基础

项目中经常有一些配置文件。比如

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

那测试它的测试用例可以这样写

import { generateConfig } from './snapshot.js'

test('测试 generateConfig', () => {
    expect(generateConfig()).toEqual({
        server: 'http://localhost',
        port: '8080'
    })
})

当配置项不断增加的时候,就需要不断去更改测试用例。

那么我们可以这样写测试用例:

import { generateConfig } from './snapshot.js'

test('测试 generateConfig', () => {
    expect(generateConfig()).toMatchSnapshot()
})

toMatchSnapshot() 会为expect 的结果做一个快照并与前面的快照做匹配。(如果前面没有快照那就保存当前生成的快照即可)

这在配置文件的测试的时候是很有用的,因为配置文件,一般不需要变化。

当然,确实要改配置文件,然后要更新快照,也可。

如下

上图说了,按‘u’ 可以更新快照(先按w,当有多个快照报错时,可以选i 一个个更新快照)。

有一种情况,假设配置项中有随机数或者当前时间,如下。

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

那case 中snapshot 就需要使用expect.any() 了,如下

import { generateConfig } from './snapshot.js'

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

之前使用snapshot 的时候,都会生成一个snapshot 的文件。

下面我们来使用行内snapshot。要使用行内snapshot ,我们需要在项目中安装 prettier

npm install prettier@1.18.2

然后,我们改一下测试用例

import { generateConfig } from "./snapshot.js";

test("测试 generateConfig", () => {
  expect(generateConfig()).toMatchInlineSnapshot(
    {
      time: expect.any(Date)
    }
  );
});

运行测试用例,会发现测试用例代码变成如下了。快照被保存到了测试代码中 

import { generateConfig } from "./snapshot.js";

test("测试 generateConfig", () => {
  expect(generateConfig()).toMatchInlineSnapshot(
    {
      time: expect.any(Date)
    },
    `
    Object {
      "port": "8080",
      "server": "http://localhost",
      "time": Any<Date>,
    }
  `
  );
});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值