开玩笑-如何在方法中测试功能

时间:2020-06-29 20:55:51

标签: node.js unit-testing jestjs babel-jest

我已经尝试了很长时间,但没有任何效果,如何测试“ 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()
  })

1 个答案:

答案 0 :(得分:0)

作为单元测试的原则,我们假设外部程序包已经过测试并且可以正常工作。不过,您可以对测试执行的操作是监视compare函数,并检查您的方法正在调用该方法以及该方法使用的是什么。

import * as bcrypt from 'bcrypt';

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

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