【问题标题】:jest - how to test a function within a method笑话 - 如何在方法中测试函数
【发布时间】:2020-10-20 02:42:32
【问题描述】:

我试了半天没用,怎么测试“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()
  })

【问题讨论】:

  • 您不需要对bcrypt.compare 进行单元测试,因为它不是您项目的一部分,而是在 bcrypt 包中进行了单元测试。如果您的 TesteService 中有一个真正的实现,那么您可以根据一些输入和预期结果对其进行单元测试。
  • 嗯好的,谢谢伙计

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


【解决方案1】:

作为单元测试的一项原则,我们假设外部包已经过测试并且正在运行。但是,您可以对测试执行的操作是监视 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');
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多