在Angular 2+单元测试中导入存根文件

问题描述

我的项目有很多实用程序功能,可以执行一些数据转换等。 这些函数不是类,而是在许多实用程序文件中重复使用。

我对角度测试非常陌生。搜索了很长时间,我找不到存根已测试文件的方法。这是示例:

/utils/helpers.ts

export const sumNumber = (a: number,b: number): number => {
  return a + b;
}

/utils/file-i-want-to-test.ts

import { sumNumber } from "./helpers";

export const sumArrays = (arr1: number[],arr2: number[]): number[] => {
  const len = arr1.length > arr2.length ? arr1.length : arr2.length;
  const result = new Array(len).fill(0);

  return result.map((_,index) => sumNumber(arr1[index] || 0,arr2[index] || 0));
}

/utils/file-i-want-to-test.spec.ts

import { sumArrays } from './file-i-want-to-test';

describe('Utilities',() => {

  describe('Function - sumArrays',() => {

    it('should return empty array',() => {
      const actual = sumArrays([],[]);
      expect(actual).toEqual([]);
    });

    it('should call sumValue 2 times',() => {
      const actual = sumArrays([1,2],[3,4]);

      // How to test that sumArray is actually calling his dependency sumNumber?
    });
  });
});

问题

为了正确地对功能 sumArrays 进行单元测试,我需要将其依赖项 sumNumber 存根。 怎么做?

解决方法

尝试一下:

import * as helpers from './helpers'; // import helpers like so

describe('Utilities',() => {

  describe('Function - sumArrays',() => {

    it('should return empty array',() => {
      const actual = sumArrays([],[]);
      expect(actual).toEqual([]);
    });

    it('should call sumValue 2 times',() => {
      spyOn(helpers,'sumNumber'); // this just stubs it to return undefined
      const actual = sumArrays([1,2],[3,4]);
      expect(helpers.sumNumber).toHaveBeenCalled(); // expect it was called
      // How to test that sumArray is actually calling his dependency sumNumber?
    });
  });
});

spyOn也具有更丰富的API,spyOn只是使其返回未定义状态。

spyOn(helpers,'sumNumber').and.callFake(/* your fake function here */); //可以调用假函数,因此每次调用sumNumber时,您都可以拥有自己的函数定义

spyOn(helpers,'sumNumber').and.returnValue(2) //调用sumNumbers时始终返回2

//也可以看到它被调用了多少次 expect(helpers.sumNumber).toHaveBeenCalledTimes(2); //两次呼叫 //可以看到被调用的内容 expect(helpers.sumNumber).toHaveBeenCalledWith([1,2]); // 1为a,2为b

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...