带有Jest的Nestjs模拟服务构造函数

问题描述 投票:0回答:1

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

sms.service.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);
    }
}

包含我的测试的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);
    });
  });
});

[如何使用SmsService构造函数的玩笑创建模拟,以便将twilio变量设置为在service.spec.js中创建的模拟版本?

typescript mocking twilio nestjs jest
1个回答
0
投票

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

创建自定义提供程序

@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();
© www.soinside.com 2019 - 2024. All rights reserved.