Typescript 构造函数属性的存根方法
我正在尝试单元测试一个使用该软件包发送SMS消息的函数。对于传入的参数和调用的时间,我尝试测试的函数是Typescript 构造函数属性的存根方法,typescript,mocha.js,twilio,sinon,chai,Typescript,Mocha.js,Twilio,Sinon,Chai,我正在尝试单元测试一个使用该软件包发送SMS消息的函数。对于传入的参数和调用的时间,我尝试测试的函数是Twilio.prototype.messages.create sendText.ts const twilio = new Twilio('ACfakeName', 'SomeAuthToken'); // Need to stub this guy try { await twilio.messages.create({body: 'something', to: `123456
Twilio.prototype.messages.create
sendText.ts
const twilio = new Twilio('ACfakeName', 'SomeAuthToken');
// Need to stub this guy
try {
await twilio.messages.create({body: 'something', to: `1234567890`, from: '1234567890' });
}
catch (e) {
console.log('An error while sending text', e);
}
twilioCreateStub = sinon.stub(Twilio.prototype.messages, 'create');
it('should call twilio.messages.create() once', async () => {
try {
await sendText();
}
catch (e) {
fail('This should not fail.')
}
expect(twilioCreateStub.callCount).to.equal(1);
});
sendText.spec.ts
const twilio = new Twilio('ACfakeName', 'SomeAuthToken');
// Need to stub this guy
try {
await twilio.messages.create({body: 'something', to: `1234567890`, from: '1234567890' });
}
catch (e) {
console.log('An error while sending text', e);
}
twilioCreateStub = sinon.stub(Twilio.prototype.messages, 'create');
it('should call twilio.messages.create() once', async () => {
try {
await sendText();
}
catch (e) {
fail('This should not fail.')
}
expect(twilioCreateStub.callCount).to.equal(1);
});
这样运行会使测试失败,callCount
为0。我不确定mocha是如何运行这些功能的,但如果测试失败,它似乎不会显示任何日志。如果我删除expect
部分,似乎调用了真正的twilio.messages.create
,因为我得到了以下日志:
An error while sending text { [Error: The requested resource /2010-04-01/Accounts/ACfakeName/Messages.json was not found]
status: 404,
message:
'The requested resource /2010-04-01/Accounts/ACfakeName/Messages.json was not found',
code: 20404,
moreInfo: 'https://www.twilio.com/docs/errors/20404',
detail: undefined }
我还尝试了
sinon.createStubInstance
,并获得了类似的结果。我看不出有任何迹象表明我正在存根深度嵌套的方法。我会将Twillio的实例注入到您的类中。然后在测试时,您可以创建类的存根:
class myClass{
constructor(twillio){
this.twilio = twilio;
}
//functions using twillio here
}
然后您可以创建一个存根:
const twilioStub = {messages: {create: sinon.stub()}}; //You might want to give this more functions and put it in a seperate file
myClass = new MyClass(twiliostub);
//call function on myClass using twilio
expect(twilioStub.messages.create.callCount).to.equal(1);
我会将Twillio的实例注入到您的类中。然后在测试时,您可以创建类的存根:
class myClass{
constructor(twillio){
this.twilio = twilio;
}
//functions using twillio here
}
然后您可以创建一个存根:
const twilioStub = {messages: {create: sinon.stub()}}; //You might want to give this more functions and put it in a seperate file
myClass = new MyClass(twiliostub);
//call function on myClass using twilio
expect(twilioStub.messages.create.callCount).to.equal(1);
为什么在测试开始时会调用存根?没有别的事发生。@DuncanBeevers你说得对,对不起。我没有很好地移动我的代码。修复了。为什么在测试开始时会调用存根?没有别的事发生。@DuncanBeevers你说得对,对不起。我没有很好地移动我的代码。修正了。这正是我最后要做的。谢谢这正是我最终要做的。谢谢