我正在嘗試模擬twilio-node庫中messages.create()方法的回傳值。
由于 create 方法位于名為messages的介面內,因此我無法直接模擬 create 方法的回傳值。
我的單元測驗:
import {
createStubInstance,
StubbedInstanceWithSinonAccessor,
} from '@loopback/testlab';
import sinon from 'sinon';
import {Twilio} from '../../../../clients/whatsapp-sms-clients/twilio.whatsapp-sms-clients';
import twilio from 'twilio';
describe('Twilio client (UnitTest)', () => {
let twilioMock: StubbedInstanceWithSinonAccessor<twilio.Twilio>;
let logger: StubbedInstanceWithSinonAccessor<LoggingService>;
let twilioClient: Twilio;
beforeEach(() => {
twilioMock = createStubInstance(twilio.Twilio);
logger = createStubInstance(LoggingService);
twilioClient = new Twilio(twilioMock, logger);
});
it('should create the message', async () => {
twilioMock.stubs.messages.create.resolves({
// mocked value
});
});
});
提前致謝。
uj5u.com熱心網友回復:
Twilio 開發人員布道者在這里。
我以前沒有像這樣使用testlab/ sinon,但我想我知道你需要做什么,如果不是正確的語法。
您需要將回應存根twilioMock.messages以回傳具有create屬性的物件,該屬性是決議為您想要的結果的存根函式。像這樣的事情可能會奏效,或者至少讓你走上正軌:
it('should create the message', async () => {
// Create stub for response to create method:
const createStub = sinon.stub().resolves({
// mocked value
});
// Stub the value "messages" to return an object that has a create property with the above stub:
twilioMock.stubs.messages.value({
create: createStub
});
// Rest of the test script
});
編輯
好的,value上面的使用不起作用。我又試了一次。此版本從示例中洗掉了您的自定義 Twilio 包裝器,而只是直接在 Twilio 客戶端存根本身上呼叫事物。希望您可以以此為靈感將其應用到您的測驗中。
我意識到這twilioClient.messages是一個吸氣劑并且是動態定義的。所以,我直接在存根客戶端上存根結果。
import {
createStubInstance,
StubbedInstanceWithSinonAccessor,
} from "@loopback/testlab";
import sinon from "sinon";
import { Twilio } from "twilio";
describe("Twilio client (UnitTest)", () => {
let twilioMock: StubbedInstanceWithSinonAccessor<Twilio>;
beforeEach(() => {
twilioMock = createStubInstance(Twilio);
});
it("should create the message", async () => {
const createStub = sinon.stub().resolves({
sid: "SM1234567",
});
sinon.stub(twilioMock, "messages").get(() => ({
create: createStub,
}));
const message = await twilioMock.messages.create({
to: "blah",
from: "blah",
body: "hello",
});
expect(message.sid).toEqual("SM1234567");
});
});
上面的測驗在我的設定中對我來說通過了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324865.html
上一篇:在Jest中模擬匯入的函式
