如何让摩卡通过testing

我有以下testing:

it.only('validation should fail', function(done) { var body = { title: "dffdasfsdfsdafddfsadsa", description: "Postman Description", beginDate: now.add(3, 'd').format(), endDate: now.add(4, 'd').format() } var rules = eventsValidation.eventCreationRules(); var valMessages = eventsValidation.eventCreationMessages(); indicative .validateAll(rules, body, valMessages) .then(function(data) { console.log("SHOULD NOT GET HERE"); should.fail("should not get here"); done(); }) .catch(function(error) { console.log("SHOULD GET HERE"); console.log(error); }); done(); }); 

testing执行path是正确的。 当我validation数据时,它会转到“不应该到这里”。 testing是真的确保它没有。 而当我input非validation数据的代码确实去“应该到这里”。 所以validation规则的工作。

我想要做的是确保testing失败,当我有错误的validation数据,并validation。 然而,当我运行它,因为它具有良好的数据validation,运行失败,但摩卡仍然标记为通过。 我希望它失败,如果执行得到“不应该得到这里”。

我试过抛出新的错误(“失败”); 以及没有运气。 在这两种情况下,它似乎也运行.catch块中的代码。

有什么build议么? 我在类似的问题中find了解决scheme。 这个问题是写的,因为这些解决scheme似乎并没有为我工作。

使用chai-as-promised ,与本地摩卡诺言处理程序。

 var chai = require('chai').use(require('chai-as-promised')); var should = chai.should(); // This will enable .should for promise assertions 

你不再需要done ,只需返回承诺。

 // Remove `done` from the line below it.only('validation should fail', function(/* done */) { var body = { title: "dffdasfsdfsdafddfsadsa", description: "Postman Description", beginDate: now.add(3, 'd').format(), endDate: now.add(4, 'd').format() } var rules = eventsValidation.eventCreationRules(); var valMessages = eventsValidation.eventCreationMessages(); // Return the promise return indicative .validateAll(rules, body, valMessages) .should.be.rejected; // The test will pass only if the promise is rejected // Remove done, we no longer need it // done(); }); 

你可以调用assert.fail

 it("should return empty set of tags", function() { assert.fail("actual", "expected", "Error message"); }); 

另外,如果使用参数调用done()函数,则Mocha认为testing失败。

例如:

 it("should return empty set of tags", function(done) { done(new Error("Some error message here")); }); 

虽然第一个看起来更清楚。

在ES2017 async / await世界chai-as-promised是不必要的。 尽pipe简单的拒绝是一个地方,但是如果您希望更详细地testing错误,那么以下设置是必需的

 it.only('validation should fail', async function(){ let body = { ... } let rules = eventsValidation.eventCreationRules() let valMessages = eventsValidation.eventCreationMessages() try { await indicative.validateAll(rules, body, valMessages) } catch (error) { return expect(error).to.be.instanceOf(Error) } expect.fail(null, null, 'validateAll did not reject with an error') // or throw new Error('validateAll did not reject with an error') }) 

需要Node.js 7.6+或Babel