我有一个带有方法的 Controller :
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: 'test@test.com',
password: 'Test12345',
confirm: 'Test12345',
username: 'Test',
};
it('it should send user data with email: test@test.com', () => {
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);
});
我检查了我的用户数据是否进入 Controller (req.user)。 我试图用 spy 查看包含 res 的内容,但没有找到我的用户数据 我不明白如何在我的情况下使用 sinon ?
最佳答案
你几乎通过了测试。对于这种测试,我们可以使用Sinon的usedWith
来检查函数和参数是否被正确调用。
describe('authController', () => {
const USER = {
email: 'test@test.com',
password: 'Test12345',
confirm: 'Test12345',
username: 'Test',
};
it('it should send user data with email: test@test.com', () => {
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;
});
});
希望有帮助。
关于javascript - express : I don't understand how to use sinon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51370338/