【问题标题】:Nestjs mocking service constructor with JestNestjs 用 Jest 模拟服务构造函数
【发布时间】:2020-05-06 09:20:42
【问题描述】:

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

【问题讨论】:

    标签: javascript typescript jestjs twilio nestjs


    【解决方案1】:

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

    创建自定义提供程序

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

    请参阅this thread,了解如何创建模拟。

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 2023-03-09
      相关资源
      最近更新 更多