【问题标题】:mocha - Retrieve result of promise testmocha - 检索承诺测试的结果
【发布时间】:2017-02-23 03:45:36
【问题描述】:

我想在before得到promise的结果

describe('unsubscribe', function() {
        var arn;
        this.timeout(10000);
        before(function(done) {
            sns.subscribe('param1', 'param2').then(
                (result) => {
                arn = result;
                done();
            },
            (error) => {
                assert.fail(error);
                done();
            });
        });
        it('("param") => promise returns object', function() {
            const result = sns.unsubscribe(arn);
            expect(result).to.eventually.be.an('object');
        });
    });

同样,在after 我想在测试中得到promise的结果

describe('subscribe', function() {
        var arn;
        this.timeout(10000);
        it('("param1","param2") => promise returns string', function(done) {
            sns.subscribe('param1', 'param2').then(
                (result) => {
                    arn = result;
                    expect(result).to.be.a('string');
                },
                (error) => {
                    assert.fail(error);
                    done();
                });
        });
        after(function(done) {
            sns.unsubscribe(arn).then(
                (result) => done());
        });
    });

这段代码是否正确编写?有没有更好的做法?推荐的方法是什么?

【问题讨论】:

    标签: javascript node.js unit-testing testing mocha.js


    【解决方案1】:

    您想让 Mocha 等待解决承诺的每个地方都应该返回承诺,而不是使用 done。所以你的before 钩子可以简化为:

        before(() => sns.subscribe('param1', 'param2')
            .then((result) => arn = result));
    

    这比在这里和那里拥有done 并且必须针对错误条件执行任何特殊操作更具可读性。如果有错误,promise 会拒绝,Mocha 会捕获它并报告错误。无需执行您自己的断言。

    你有一个测试和一个after 钩子,也可以通过返回他们使用的承诺而不是使用done 来简化。如果你的测试依赖于一个承诺,记得返回它。您在一项测试中忘记了它:

    it('("param") => promise returns object', function() {
      const result = sns.unsubscribe(arn);
      // You need the return on this next line:
      return expect(result).to.eventually.be.an('object');
    });
    

    提示:如果您有一个所有测试都是异步的测试套件,您可以使用--async-only 选项。这将使 Mocha 要求所有测试调用 done 或返回一个承诺,并且可以帮助捕获您忘记返回承诺的情况。 (否则,如果不引发任何错误,这种情况很难。)

    describe 的回调中定义一个变量并将其设置在before/beforeEach 钩子之一中并在after/afterEach 钩子中检查它是在钩子和测试之间传递数据的标准方法。 Mocha 没有为此提供特殊设施。所以,是的,如果您需要传递作为承诺结果的数据,您需要像您一样在.then 中执行分配。您可能会遇到一些示例,其中人们不使用在describe 回调中定义的变量,而是在this 上设置字段。哦,这行得通,但 IMO 它很脆弱。一个超级简单的例子:如果您设置this.timeout 记录一些仅对您的测试有意义的数字,那么您已经覆盖了 Mocha 提供的用于更改其超时的函数。您可以使用另一个现在不冲突但在发布新版本的 Mocha 时会发生冲突的名称。

    【讨论】:

    • 感谢您的正确回答。还有一个问题:如果在测试中返回的一个承诺的结果有很多expect。什么时候退?
    • chai-as-promised 的断言是承诺,因此您可以使用then 将它们链接为任何承诺。你可以有return expect(result).to.eventually.be.an("object").then(() => expect(otherResult).to.eventually.be.whatever)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    相关资源
    最近更新 更多