使用mocha

时间:2017-02-25 06:41:00

标签: javascript node.js promise mocha sinon

我想为承诺拒绝案件制作测试案例。

这是我的代码

1)文件:TemplateFinder.js

**I want to make test for this method on promise reject using *mocha* how can i achieve this?**

var findTemplate = function (template) {

    return templateFinder.find(templateName)
        .then( (result) => {
            return result.id;
        });
};

2)query.js

var find = function (template) {
    return knex.where({
        internal_name: template,
    })
    .select('external_id')
    .from('mailing_external_template')
    .then(function (data) {
        if (0 === data.length) {
            return Promise.reject(RangeError('no result for id'));
        } else {
            return data[0].external_id;
        }
    });
};

3)app.js

Main file to run

function findTemplate()
{
    templateFinder.findGoodTemplate('good-mail-template');
}

initiateProcess()
.then(function (fromResolve) {
    return findTemplate();
})
.catch(function (e) {

});

我的尝试:

it('should throw error if template not found', function () {

    var findTemplateIdStub = sinon.stub(templateFinder, 'find');

    var error = 'my expected error message returned by my function';
    findTemplateIdStub.returns(Promise.reject(error));

    return templateFinder.findTemplate(templateName)
      .catch(function(err) {
        assert.equal(err, error);
      });
  });

我的尝试的问题是findTemplate没有捕获,所以我如何断言我的测试用例中的变量,而不是原始的。 (Catch不在代码中,但仍然是我的测试通过。)请帮我为findTemplate拒绝案例制作测试用例。

1 个答案:

答案 0 :(得分:0)

findTemplateIdStub是否应该返回承诺?

如果是这种情况,您可以包含sinon-as-promised ,存根应该是:

findTemplateIdStub.rejects('some error')表示不良案例

好的案例

findTemplateIdStub.resolves(1234)