该
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)中用于表示实例字段。因此,当与方法名称一起使用时,它表示在类的实例上调用的方法(而不是类方法,该方法称为在类本身上)。测试套件在没有
#。)的情况下也可以正常运行。
提供横幅
摩卡(Mocha)的一些记者会在您
describe制作的报告中显示您的名字。例如,
spec报告者(可以通过运行来使用
$ mocha -Rspec)将报告:
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 --grepBar,并获得输出:
Bar #clone ✓ clones the object 1 passing (4ms)
或者,如果您只关心
clone所有类的方法,则
$ mocha -R spec --grep 'bcloneb'获取输出:
Foo #clone ✓ clones the object Bar #clone ✓ clones the object 2 passing (5ms)
给出的值
--grep被解释为正则表达式,因此当我通过时,我
bcloneb只要求输入单词
clone,而不要求诸如
clones或之类的东西
cloned。
提供挂钩
在上面的示例中,
beforeEachand
afterEach调用是挂钩。每个挂钩都会影响作为挂钩父项的呼叫
it内部的
describe呼叫。各种钩子是:
beforeEach``it
在describe
通话中每个人之前运行。afterEach``it
在describe
通话中每个人之后运行。before
它会it
在describe
调用中的任何个人运行之前运行一次。after``it
在describe
调用中的所有个人都运行之后,该命令将运行一次。
这些挂钩可用于获取测试所需的资源或创建测试所需的数据结构,然后在测试完成后释放资源或销毁这些结构(如果需要)。
您在问题末尾显示的摘录不会产生错误,但实际上不包含任何测试,因为测试由定义
it。



