(十)snapshot快照测试
1、快照测试
项目中经常有一些配置文件。比如
export const generateConfig = ()=>{ return { server :'http://localhost', port:'8080', domain:'localhost' } }
对应它的测试用例可以这样写 snapshot.test.js
import { generateConfig } from "./snapshot.js";
test('测试 generateConfig', () => {
expect(generateConfig()).toEqual({
server: 'http://localhost',
port: '8080',
domain:'localhost'
})
})
当配置项不断增加的时候,就需要不断去更改测试用例。
那么我们可以使用快照写测试用例:
test('测试 generateConfig', () => {
expect(generateConfig()).toMatchSnapshot()
})
运行测试用例之后会自动生成快照文件,对应目录如下:

toMatchSnapshot() 会为expect 的结果做一个快照并与前面的快照做匹配。(如果前面没有快照那就保存当前生成的快照即可)
这在配置文件的测试的时候是很有用的,因为配置文件,一般不需要变化。
当然,确实要改配置文件,然后要更新快照,也可。
2、配置文件修改
如果配置文件发生变化,运行时时会提示已经发生变化,可以根据提示的命令确定修改文件:‘npm test -- -u’

如果添加new Date()这样的参数,配置文件在实时的更新,如何处理呢?对应代码如下:
snapshot.js
export const generateConfig = () => {
return {
server: 'http://localhost',
port: '8080',
domain:'localhost',
time:new Date()
}
}
测试用例snapshot.test.js
import { generateConfig } from "./snapshot.js";
test('测试 generateConfig', () => {
expect(generateConfig()).toMatchSnapshot({
time :expect.any(Date)//Date String Number等等
})
})
3、行内快照
首先需要安装 prettier ,否则行内快照无法执行。
安装命令:npm install prettier
安装完成之后,修改测试用例:
test("测试 generateConfig", () => {
expect(generateConfig()).toMatchInlineSnapshot(
{
time: expect.any(Date),
}
);
});
运行测试用例之后,会多出一个参数来,结果如下:
test("测试 generateConfig", () => {
expect(generateConfig()).toMatchInlineSnapshot(
{
time: expect.any(Date),
},
`
Object {
"domain": "localhost",
"port": "8080",
"server": "http://localhost",
"time": Any<Date>,
}
`
);
});
浙公网安备 33010602011771号