我正在为我在express中创建的模块编写一个Mocha测试。它给了我一个错误,我不明白如何解决。
测试:
describe('userController', function() {
describe('post -> /create', function() {
it('A user should be created', () => {
var testRequest = {
body: {
password:"pass1",
email:"test@me.com",
username:"user1",
}
};
database.registerUser(testRequest, (callBack) => {
new User({email:"test@me.com"})
.fetch()
.then((model) => {
assert.equal(model.get('password'), testRequest.body.password);
})
.catch((err) => {
assert(false);
});
});
});
});
});
错误:
Unhandled rejection AssertionError: false == true
at User.fetch.then.catch (/home/shanedrafahl/code/MyRentalServer/myRental/test/test.js:72:17)
at tryCatcher (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/promise.js:689:18)
at Async._drainQueue (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/home/shanedrafahl/code/MyRentalServer/myRental/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)
如果有人可以告诉我或告诉我为什么它会给我这个错误以及如何解决它我会很感激。
答案 0 :(得分:2)
我认为你有两个问题。首先是实际问题。第二个是测试的问题。也许解决第二个问题会为你提供更多如何解决第一个问题的信息。
我不熟悉assert
,但从您的堆栈跟踪判断,您似乎期望assert
在此部分执行其他操作:
.catch((err) => {
assert(false); // <---- test problem is with the first param being false
});
我认为您真正想要的是打印err
的内容。有了它,您就可以理解为什么到达catch
。
由于您的测试是异步的,我认为您应该使用done
,如下所示:
it('A user should be created', (done) => { //added done param
...
.then((model) => {
assert.equal(model.get('password'), testRequest.body.password);
done() // let mocha know the async test is done
})
.catch((err) => {
done(err) // let mocha know the async test is done with an error, so it can display the error in the output
});
现在,您应该能够测试代码以找到其他问题。
您可以阅读有关使用Mocha here: Mocha - Asynchronous Code
的异步测试