我想帮助确定为什么sails.js应用中的单元测试无法按预期工作。
我在sails.js app上使用mocha,chai和bluebird promise库。
我想要实现的目标:
我目前拥有的内容:
// Test the 'create' method
describe('Method \'create\' test result: \n', function () {
// Test that name is required and less than 121 chars long
it('Must receive the name parameter and be less than 121 chars long', function(done) {
// It should not accept any of the following names
var names = ['',' ','thisstringislongerthanthemaxof121characterslongthisstringislongerthanthemaxof121characterslongthisstringislongerthanthema',[],[{}],[{test: 'test'}],'wrongchars*[]$£%fsf','$%@~}[','£$%jkdfi',' $%"£asdwdFDE','hD8U £$&{DS ds'];
sails.bluebird.each(names,function(name){
TagsService.create(name).then(function(data){
assert.propertyVal(data,'status','err','An error was NOT returned - even though names provided should be invalid');
});
}).then(function(){
done();
});
});
});
即使传入有效名称或从方法返回null,它似乎也会传递。
答案 0 :(得分:5)
好吧,看起来我经过多次试验和错误后设法解决了这个问题。
结果我需要在执行每个方法后从Promise捕获done()回调。还需要返回从TagsService promise对象完成的测试结果。 (仍然不是100%确定这是考虑它的正确方法..)。无论如何,测试似乎现在正常运作。
这是我的结果:
var names = ['',' ','thisstringislongerthanthemaxof121characterslongthisstringislongerthanthemaxof121characterslongthisstringislongerthanthema',[],[{}],[{test: 'test'}],'wrongchars*[]$%fsf','$%@~}[','�$%jkdfi',' $%"�asdwdFDE','hD8U �$&{DS ds'];
sails.bluebird.each(names, function(name){
return TagsService.create(name).then(function(data) {
assert.property(data, 'status', 'create method did not return a status property');
assert(data.status === 'err', 'even with an invalid name parameter passed - it did not return an err status, which it must do with an invalid name.');
});
}).then(function(){
done();
}).catch(done);