在Mocha中describe()的作用是什么?
Mocha官方站点上的文档包含以下示例:
describe('User', function(){ describe('#save()', function(){
it('should save without error', function(done){
var user = new User('Luna');
user.save(function(err){
if (err) throw err;
done();
});
})
})
})
我想知道什么时候应该将测试嵌套在describe函数中以及其基本目的describe是什么。我可以比较传递给describe编程语言的注释的第一个参数吗?describe控制台的输出中未显示任何内容。是仅出于可读性目的,还是该功能还有其他用途?
如果我这样使用,有什么问题吗?
describe('User', function(){ describe('#save()', function(){
var user = new User('Luna');
user.save(function(err){
if (err) throw err;
done();
})
})
})
如果我这样做,则测试仍会通过。
回答:
该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 -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。
提供挂钩
在上面的示例中,beforeEachand
afterEach调用是挂钩。每个挂钩都会影响作为挂钩父项的呼叫it内部的describe呼叫。各种钩子是:
beforeEach``it在describe通话中每个人之前运行。afterEach``it在describe通话中每个人之后运行。before它会it在describe调用中的任何个人运行之前运行一次。after``it在describe调用中的所有个人都运行之后,该命令将运行一次。
这些挂钩可用于获取测试所需的资源或创建测试所需的数据结构,然后在测试完成后释放资源或销毁这些结构(如果需要)。
您在问题末尾显示的摘录不会产生错误,但实际上不包含任何测试,因为测试由定义it。
以上是 在Mocha中describe()的作用是什么? 的全部内容, 来源链接: utcz.com/qa/430307.html

