gpt4 book ai didi

node.js - 测试函数时替换变量的值

转载 作者:行者123 更新时间:2023-11-28 21:16:24 24 4
gpt4 key购买 nike

我有一个记录用户数据并给出唯一标识符的路由。

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() 的行为,您可以使用 sinon .如果您决定采用这种方式,则必须在测试文件 + 模块中要求 sinon,其中 serviceSidVerification 所在。然后,在执行测试之前,您必须执行如下操作:

const stubServiceSidVerification = sinon.stub(yourModule, 'serviceSidVerification')
.returns('yourValue');

请注意,如果您使用 sinonserviceSidVerification 应该作为对象的属性导出,而不是作为独立函数导出,因为 issue .

另一种选择是使用 proxyquire .

关于node.js - 测试函数时替换变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57456446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com