开玩笑 - 如何在方法中测试函数

jest - how to test a function within a method

试了很久都没用,请问如何测试“methodName”方法中的“compare”函数?

teste.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { TesteService } from './teste.service';

describe('TesteService', () => {
  let service: TesteService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [TesteService],
    }).compile();

    service = module.get<TesteService>(TesteService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  it('methodName need return a string', () => {
    expect(service.methodName()).toEqual(typeof String)
  })  
});

teste.ts

import { Injectable } from '@nestjs/common';
import { compare } from 'bcrypt'

@Injectable()
export class TesteService {

  methodName() {
    const password  = '123456789'
    
    const checkPassword = compare('123456789', password)

    return checkPassword ? 'correct' : 'wrong'
  }

}

如果我这样做可以吗?

 it('compare password', () => {
    const checkPassword = compare('123456789', '123456789')

    expect(checkPassword).toBeTruthy()
  })

作为单元测试的原则,我们假设外部包已经过测试并且可以正常工作。不过,您可以对测试做的是监视比较函数并检查您的方法是否正在调用它以及它正在调用什么。

import * as bcrypt from 'bcrypt';

it('should call compare', () => {
  const spyCompare = jest.spyOn(bcrypt, 'compare');
  service.methodName();

  expect(spyCompare).toHaveBeenCalled();
  expect(spyCompare).toHaveBeenCalledWith('123456789');
})