Nestjs 用 Jest 模拟服务构造函数



我创建了以下服务来使用twilio向用户发送登录代码短信:

短信服务网

import { Injectable, Logger } from '@nestjs/common';
import * as twilio from 'twilio';
Injectable()
export class SmsService {
private twilio: twilio.Twilio;
constructor() {
this.twilio = this.getTwilio();
}
async sendLoginCode(phoneNumber: string, code: string): Promise<any> {
const smsClient = this.twilio;
const params = {
body: 'Login code: ' + code,
from: process.env.TWILIO_SENDER_NUMBER,
to: phoneNumber
};
smsClient.messages.create(params).then(message => {
return message;
});
}
getTwilio() {
return twilio(process.env.TWILIO_SID, process.env.TWILIO_SECRET);
}
}

sms.service.spec.js包含我的测试

import { Test, TestingModule } from '@nestjs/testing';
import { SmsService } from './sms.service';
import { Logger } from '@nestjs/common';
describe('SmsService', () => {
let service: SmsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SmsService]
}).compile();
service = module.get<SmsService>(SmsService);
});
describe('sendLoginCode', () => {
it('sends login code', async () => {
const mockMessage = {
test: "test"
}
jest.mock('twilio')
const twilio = require('twilio');
twilio.messages = {
create: jest.fn().mockImplementation(() => Promise.resolve(mockMessage))
}
expect(await service.sendLoginCode("4389253", "123456")).toBe(mockMessage);
});
});
});

如何使用 jest create mock 的SmsService构造函数,以便twilio变量设置为我在service.spec.js中创建的它的模拟版本?

你应该注入你的依赖而不是直接使用它,然后你可以在测试中模拟它:

创建自定义提供程序

@Module({
providers: [
{
provide: 'Twillio',
useFactory: async (configService: ConfigService) =>
twilio(configService.TWILIO_SID, configService.TWILIO_SECRET),
inject: [ConfigService],
},
]

将其注入到您的服务中

constructor(@Inject('Twillio') twillio: twilio.Twilio) {}

在测试中模拟它

const module: TestingModule = await Test.createTestingModule({
providers: [
SmsService,
{ provide: 'Twillio', useFactory: twillioMockFactory },
],
}).compile();

请参阅此线程,了解如何创建模拟。

最新更新