Node.js 测试函数时替换变量的值
我有一个记录用户数据并提供唯一标识符的路由Node.js 测试函数时替换变量的值,node.js,testing,mocha.js,chai,Node.js,Testing,Mocha.js,Chai,我有一个记录用户数据并提供唯一标识符的路由 router.post('/', (req, res) => { const user_email = req.body.user_email; const username = req.body.username; const user_phone = req.body.user_phone; const service_sid = serviceSidVerification(user_phone);
router.post('/', (req, res) => {
const user_email = req.body.user_email;
const username = req.body.username;
const user_phone = req.body.user_phone;
const service_sid = serviceSidVerification(user_phone);
const entry_id = uuidv4();
const user = new User(
username,
user_email,
user_password,
user_phone,
entry_id,
service_sid,
);
await db.query(user.setUser());
return res.status(200).json({
entry_id: entry_id,
});
});
我想为这条路线写一个测试。我需要用我自己的函数替换serviceSidVerification()
函数的返回值。例如,12345
。如何通过测试做到这一点
这就是我的测试结果
describe(`Users Test`, () => {
describe('POST /api/users/', () => {
it(`Should create user`, (done) => {
let stub = sinon.createStubInstance(server);
stub.getEvents.returns('12345')
chai
.request(server)
.post('/api/users/')
.send({ 'username': faker.internet.userName() })
.send({ 'user_email': faker.internet.email() })
.send({ 'user_password': faker.internet.password() })
.send({ 'user_phone': faker.phone.phoneNumber() })
.end((err, res) => {
expect(res).have.status(200);
expect(res.body).have.property('entry_id');
expect(res.body.entry_id).to.be.an('string');
done();
});
});
});
});
});
...
function ServiceSidVerification(phone) {
const client = new twilio(config.smsVerify.accountSid, config.smsVerify.authToken);
const service_sid = (await client.verify.services
.create({
friendlyName: config.smsVerify.title,
codeLength: config.smsVerify.codeLength,
})
).sid;
const sid = (await client.verify.services(service_sid).verifications
.create({
to: phone,
channel: 'sms'
})
).sid;
return { service_sid, sid };
}
如何测试路由?要更改
serviceSidVerification()
的行为,可以使用。如果您决定这样做,您必须在测试文件+模块中要求serviceSidVerification
驻留的sinon
。然后,在执行测试之前,您必须执行以下操作:
const stubServiceSidVerification = sinon.stub(yourModule, 'serviceSidVerification')
.returns('yourValue');
请注意,如果使用sinon
,serviceSidVerification
应作为对象的属性导出,而不是作为独立函数导出
另一个选项是使用。我收到一个错误
无法存根不存在的自有属性serviceSidVerification
是否可以共享定义和导出serviceSidVerification
的代码以及尝试存根的代码?添加。函数在同一个文件中。当测试调用使用该函数的API时,sinon
可以做的是存根(替换)指定的函数。在您的情况下,当测试到达端点时,它可能会更改serviceSidVerification
的行为。为了做到这一点,该函数必须是必需的,并在执行测试的地方存根。您说过,serviceSidVerification
是在“同一文件”中定义的,您指的是什么文件?而且,我看不出它在哪里被打到。我看到了sinon.createStubInstance(server)
,但我不确定这是否是这种情况下需要的。我不知道如何测试此路由。有没有一个例子或解释?