Rob*_*ers 25 javascript mocha.js node.js
我有以下测试:
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();
});
Run Code Online (Sandbox Code Playgroud)
测试执行路径是正确的.当我验证数据时,它会"不应该在这里".测试真的是确保它没有.当我输入非验证数据时,代码会转到"应该在这里".因此验证规则有效.
我正在尝试做的是确保当我有错误的验证数据并且验证时测试失败.然而,当我运行它,因为它有良好的数据,它验证,运行失败,但摩卡仍然标记为传递.如果执行"不应该在这里",我希望它失败.
我试过抛出新的错误("失败"); 也没有运气.在这两种情况下,它实际上似乎也在.catch块中运行代码.
有什么建议?我在类似的问题中找到了解决方案.写这个问题是因为这些解决方案似乎对我不起作用.
Mon*_*Kin 41
你可以打电话assert.fail:
it("should return empty set of tags", function()
{
assert.fail("actual", "expected", "Error message");
});
Run Code Online (Sandbox Code Playgroud)
此外,如果done()使用参数调用函数,Mocha会认为测试失败.
例如:
it("should return empty set of tags", function(done)
{
done(new Error("Some error message here"));
});
Run Code Online (Sandbox Code Playgroud)
虽然第一个看起来更清晰.
Yur*_*bin 14
使用chai-as-promised,使用本机Mocha承诺处理程序.
var chai = require('chai').use(require('chai-as-promised'));
var should = chai.should(); // This will enable .should for promise assertions
Run Code Online (Sandbox Code Playgroud)
您不再需要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();
});
Run Code Online (Sandbox Code Playgroud)
在ES2017 async/ await世界chai-as-promised中不需要那么多.虽然简单的拒绝是一个地方chai-as-promised使用起来有点整洁,但catch如果你想更详细地测试错误,则需要a .
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) {
expect(error).to.be.instanceOf(Error)
expect(error.message).to.match(/Oh no!/)
return
}
expect.fail(null, null, 'validateAll did not reject with an error')
// or throw new Error('validateAll did not reject with an error')
})
Run Code Online (Sandbox Code Playgroud)
async/ await需要Node.js 7.6+或像Babel这样的编译器
小智 6
这个简单的投掷对我有用
describe('Lead', () => {
it('should create a new lead', async () => {
throw 'not implemented'
})
})
Run Code Online (Sandbox Code Playgroud)