项目中经常有一些配置文件。比如
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 [email protected]
然后,我们改一下测试用例
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,
}
`
);
});