问题
I'm having some trouble with getting a simple async test working. The following piece of code doesn't throw any errors in the console, even though it should, because the data
passed to the function does not equal 0
:
define([
'intern!bdd',
'intern/chai!expect'
], function (bdd, expect) {
with (bdd) {
describe('Test', function () {
it('async test', function(){
var dfd = this.async(2000);
var wait = function(ms) {
setTimeout(function(){
dfd.resolve('test');
}, ms);
return dfd.promise;
};
wait(1500).then(dfd.callback(function (data) {
// data === 'test', so this should fail.
expect(data).to.equal(0);
}), dfd.reject.bind(dfd));
});
});
}
});
I'm pretty sure I messed up somewhere because I never worked with promises until now, but I can't figure out where. Any ideas would help a lot. Thanks!
回答1:
You’re using the same Deferred object for two different asynchronous operations and resolving it (= successful test) the first time. You need to create your own separate Deferred object for the wait function:
define([
'intern!bdd',
'intern/chai!expect',
'intern/node_modules/dojo/Deferred'
], function (bdd, expect, Deferred) {
with (bdd) {
describe('Test', function () {
it('async test', function(){
var dfd = this.async(2000);
var wait = function(ms) {
var waitDfd = new Deferred();
setTimeout(function(){
waitDfd.resolve('test');
}, ms);
return waitDfd.promise;
};
wait(1500).then(dfd.callback(function (data) {
// data === 'test', so this should fail.
expect(data).to.equal(0);
}), dfd.reject.bind(dfd));
});
});
}
});
来源:https://stackoverflow.com/questions/17423749/async-test-doesnt-error-on-fail