快照测试
【Snapshot testing】
快照测试允许将任意值序列化为字符串值,并与一组已知的良好值进行比较。已知的良好值被称为快照,并存储在快照文件中。快照文件由测试运行器管理,但设计为可供人类阅读,以便调试。最佳做法是将快照文件与测试文件一起提交到源代码管理中。
【Snapshot tests allow arbitrary values to be serialized into string values and compared against a set of known good values. The known good values are known as snapshots, and are stored in a snapshot file. Snapshot files are managed by the test runner, but are designed to be human readable to aid in debugging. Best practice is for snapshot files to be checked into source control along with your test files.】
快照文件是通过使用 --test-update-snapshots 命令行标志启动 Node.js 时生成的。每个测试文件都会生成一个单独的快照文件。默认情况下,快照文件的名称与测试文件相同,并且使用 .snapshot 文件扩展名。此行为可以通过 snapshot.setResolveSnapshotPath() 函数进行配置。每个快照断言对应快照文件中的一个导出项。
【Snapshot files are generated by starting Node.js with the
--test-update-snapshots command-line flag. A separate snapshot file is
generated for each test file. By default, the snapshot file has the same name
as the test file with a .snapshot file extension. This behavior can be
configured using the snapshot.setResolveSnapshotPath() function. Each
snapshot assertion corresponds to an export in the snapshot file.】
下面展示了一个快照测试的示例。第一次执行此测试时,它会失败,因为相应的快照文件不存在。
【An example snapshot test is shown below. The first time this test is executed, it will fail because the corresponding snapshot file does not exist.】
// test.js
suite('suite of snapshot tests', () => {
test('snapshot test', (t) => {
t.assert.snapshot({ value1: 1, value2: 2 });
t.assert.snapshot(5);
});
}); 通过运行带有 --test-update-snapshots 的测试文件来生成快照文件。测试应该通过,并且在与测试文件相同的目录下会创建一个名为 test.js.snapshot 的文件。快照文件的内容如下所示。每个快照由测试的全名和一个计数器标识,用于区分同一测试中的不同快照。
【Generate the snapshot file by running the test file with
--test-update-snapshots. The test should pass, and a file named
test.js.snapshot is created in the same directory as the test file. The
contents of the snapshot file are shown below. Each snapshot is identified by
the full name of test and a counter to differentiate between snapshots in the
same test.】
exports[`suite of snapshot tests > snapshot test 1`] = `
{
"value1": 1,
"value2": 2
}
`;
exports[`suite of snapshot tests > snapshot test 2`] = `
5
`; 一旦快照文件创建完成,再次运行测试,不要使用 --test-update-snapshots 标志。现在测试应该可以通过了。
【Once the snapshot file is created, run the tests again without the
--test-update-snapshots flag. The tests should pass now.】