快照测试
¥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.