【发布时间】:2017-04-19 14:16:16
【问题描述】:
tl;博士
我正在尝试使用 mocha、chai、chai-spies 和 测试 express 应用 >重新布线。
特别是,我试图做的是模拟模块中存在的函数并使用 chai spy 代替。
我的设置
我有一个名为 db.js 的模块,它导出一个 saveUser() 方法
db.js
module.exports.saveUser = (user) => {
// saves user to database
};
app.js模块需要db模块
app.js
const db = require('./db');
module.exports.handleSignUp = (email, password) => {
// create user object
let user = {
email: email,
password: password
};
// save user to database
db.saveUser(user); // <-- I want want to mock this in my test !!
};
最后在我的测试文件app.test.js我有以下内容
app.test.js
const chai = require('chai')
, spies = require('chai-spies')
, rewire = require('rewire');
chai.use(spies);
const expect = chai.expect;
// Mock the db.saveUser method within app.js
let app = rewire('./app');
let dbMock = {
saveUser: chai.spy()
};
app.__set__('db', dbMock);
// Perform the test
it('should call saveUser', () => {
let email = 'someone@example.com'
, password = '123456';
// run the method we want to test
app.handleSignUp(email, password);
// assert that the spy is called
expect(dbMock.saveUser).to.be.spy; // <--- this test passes
expect(dbMock.saveUser).to.have.been.called(); // <--- this test fails
});
我的问题
我的问题是我确保间谍被 app.handleSignUp 调用的测试失败如下
AssertionError: expected { Spy } to have been called at Context.it (spies/app.test.js:25:40)
我感觉我做错了什么,但我现在卡住了。感谢您的帮助,谢谢
【问题讨论】:
标签: javascript node.js testing mocking chai