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

时间:2020-01-20 11:11:07

标签: javascript typescript jestjs twilio nestjs

我创建了以下服务,以使用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构造函数的jest create模拟,以便将twilio变量设置为在service.spec.js中创建的模拟版本?

0 个答案:

没有答案