Nestjs 使用 Jest 模拟服务构造函数

use*_*304 6 javascript twilio typescript jestjs nestjs

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

短信服务.ts

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

包含我的测试的 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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

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

Kim*_*ern 9

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

创建自定义提供程序

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

将其注入您的服务中

constructor(@Inject('Twillio') twillio: twilio.Twilio) {}
Run Code Online (Sandbox Code Playgroud)

在你的测试中模拟它

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

请参阅有关如何创建模拟的线程