我有一个控制器方法:
registration(req, res) {
if (!req.user) return res.status(401).send('Registration failed');
const { user } = req;
return res.status(201).json({ user });
},
我想测试使用我的假数据发送json的注册方法。
const { expect } = require('chai');
const sinon = require('sinon');
const authController = require(...);
describe('authController', () => {
const USER = {
email: '[email protected]',
password: 'Test12345',
confirm: 'Test12345',
username: 'Test',
};
it('it should send user data with email: [email protected]', () => {
const req = { user: USER };
const res = {
status: sinon.stub().returnsThis(),
json: sinon.spy(),
};
console.log('RES: ', res); // I can't see the json data
authController.registration(req, res);
expect(res.json).to.equal(USER);
});
我检查了我的USER的数据进入控制器(req.user)。我试着用spy查看包含res的内容,但是没有找到我的USER数据我不明白如何在我的情况下使用sinon?
你几乎完成了测试。对于这种测试,我们可以使用Sinon的calledWith
来检查被正确调用的函数和参数。
describe('authController', () => {
const USER = {
email: '[email protected]',
password: 'Test12345',
confirm: 'Test12345',
username: 'Test',
};
it('it should send user data with email: [email protected]', () => {
const req = { user: USER };
const res = {
status: sinon.stub().returnsThis(),
json: sinon.spy(),
};
authController.registration(req, res);
// this is how we check that the res is being called with correct arguments
expect(res.status.calledWith(201)).to.be.ok;
expect(res.json.calledWith({ user: USER })).to.be.ok;
});
});
希望能帮助到你。