it 调用会识别每个单独的测试,但 it 本身并不会告诉 Mocha 您的测试套件是如何结构化的。您如何使用describe 调用为您的测试套件提供了结构。以下是使用describe 构建测试套件为您做的一些事情。下面是一个测试套件的示例,为了讨论而进行了简化:
function Foo() {
}
describe("Foo", function () {
var foo;
beforeEach(function () {
foo = new Foo();
});
describe("#clone", function () {
beforeEach(function () {
// Some other hook
});
it("clones the object", function () {
});
});
describe("#equals", function () {
it("returns true when the object passed is the same", function () {
});
it("returns false, when...", function () {
});
});
afterEach(function () {
// Destroy the foo that was created.
// foo.destroy();
});
});
function Bar() {
}
describe("Bar", function () {
describe("#clone", function () {
it("clones the object", function () {
});
});
});
想象一下Foo 和Bar 是成熟的课程。 Foo 有 clone 和 equals 方法。 Bar 有 clone。我上面的结构是为这些类构建测试的一种可能方法。
(# 表示法被某些系统(例如,jsdoc)用来表示实例字段。因此,当与方法名称一起使用时,它表示在类的实例上调用的方法(而不是class 方法,它在类本身上调用)。测试套件在没有# 的情况下也可以运行。)
提供横幅
Mocha 的一些记者会在他们制作的报告中显示您给describe 的名字。例如,spec 报告器(您可以通过运行 $ mocha -R spec 来使用它)会报告:
Foo
#clone
✓ clones the object
#equals
✓ returns true when the object passed is the same
✓ returns false, when...
Bar
#clone
✓ clones the object
4 passing (4ms)
帮助选择要运行的部件
如果您只想运行部分测试,可以使用--grep 选项。所以如果你只关心Bar类,你可以做$ mocha -R spec --grep Bar,并得到输出:
Bar
#clone
✓ clones the object
1 passing (4ms)
或者如果你只关心所有类的clone方法,那么$ mocha -R spec --grep '\bclone\b'并得到输出:
Foo
#clone
✓ clones the object
Bar
#clone
✓ clones the object
2 passing (5ms)
给--grep 的值被解释为一个正则表达式,所以当我通过\bclone\b 时,我只询问clone 这个词,而不是clones 或cloned 之类的东西。
提供挂钩
在上面的示例中,beforeEach 和 afterEach 调用是挂钩。每个钩子都会影响 describe 调用中的 it 调用,该调用是钩子的父级。各种钩子是:
beforeEach 在describe 调用中的每个it 之前运行。
afterEach 在 describe 调用中的每个 it 之后运行。
before 在describe 调用中的任何单个it 运行之前运行一次。
after 在 describe 调用中的所有单个 it 运行后运行一次。
这些钩子可用于获取资源或创建测试所需的数据结构,然后在测试完成后释放资源或销毁这些结构(如果需要)。
您在问题末尾显示的 sn-p 不会产生错误,但它实际上不包含任何测试,因为测试是由 it 定义的。