admin管理员组

文章数量:1204006

I have created following service to use twilio send login code sms to users:

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 that contains my test

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]
    })pile();
    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);
    });
  });
});

How can I use jest create mock of the SmsService constructor so that it's twilio variable gets set to mocked version of it I create in service.spec.js?

I have created following service to use twilio send login code sms to users:

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 that contains my test

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);
    });
  });
});

How can I use jest create mock of the SmsService constructor so that it's twilio variable gets set to mocked version of it I create in service.spec.js?

Share Improve this question edited Jan 20, 2020 at 13:04 Kim Kern 60.4k20 gold badges216 silver badges212 bronze badges asked Jan 20, 2020 at 11:11 user3482304user3482304 3012 gold badges3 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

You should inject your dependency instead of using it directly, then you can mock it in your test:

Create a custom provider

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

Inject it in your service

constructor(@Inject('Twillio') twillio: twilio.Twilio) {}

Mock it in your test

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

See this thread on how to create mocks.

本文标签: javascriptNestjs mocking service constructor with JestStack Overflow