gpt4 book ai didi

node.js - 在 Mocha 中 describe() 的作用是什么?

转载 作者:IT老高 更新时间:2023-10-28 21:50:53 24 4
gpt4 key购买 nike

位于 the official Mocha site 的文档包含这个例子:

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 () {
});
});
});

想象一下 FooBar 是成熟的类。 Foocloneequals 方法。 Barclone。我上面的结构是为这些类构建测试的一种可能方法。

(# 表示法被某些系统(例如,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,而不是像 clonescloned 这样的东西。

提供 Hook

在上面的示例中,beforeEachafterEach 调用是 Hook 。每个钩子(Hook)都会影响 describe 调用内部的 it 调用,该调用是钩子(Hook)的父级。各种钩子(Hook)是:

  • beforeEachdescribe 调用中的每个单独的 it 之前运行。

  • afterEachdescribe 调用中的每个单独的 it 之后运行。

  • beforedescribe 调用中的任何单个 it 运行之前运行一次。

  • afterdescribe 调用中的所有单个 it 运行后运行一次。

这些钩子(Hook)可用于获取资源或创建测试所需的数据结构,然后在测试完成后释放资源或销毁这些结构(如果需要)。

您在问题末尾显示的代码段不会产生错误,但它实际上不包含任何测试,因为测试是由 it 定义的。

关于node.js - 在 Mocha 中 describe() 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19298118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com