簡體   English   中英

Nestjs 使用 Jest 模擬服務構造函數

[英]Nestjs mocking service constructor with Jest

我創建了以下服務來使用 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);
    }
}

包含我的測試的 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構造函數的 jest create mock 以便將它的twilio變量設置為我在service.spec.js創建的它的twilio版本?

您應該注入您的依賴項而不是直接使用它,然后您可以在測試中模擬它:

創建自定義提供程序

@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();

請參閱有關如何創建模擬的線程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM