【问题标题】:Stub file imports in Angular 2+ Unit TestingAngular 2+ 单元测试中的存根文件导入
【发布时间】:2021-01-21 02:07:08
【问题描述】:

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

我对角度测试很陌生。搜索了很长一段时间,我找不到一种方法来存根测试文件的导入。示例如下:

/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。 怎么做?

【问题讨论】:

    标签: angular typescript unit-testing stubbing angular-unit-test


    【解决方案1】:

    试试这个:

    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 */); // 可以调用 fake 所以每次调用 sumNumber 时,你都可以有自己的函数定义

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

    //也可以查看调用了多少次 expect(helpers.sumNumber).toHaveBeenCalledTimes(2); // 调用了两次 // 可以看到它被调用了什么 expect(helpers.sumNumber).toHaveBeenCalledWith([1, 2]); // 1 是 a,2 是 b

    【讨论】:

    • 嗨。感谢您的详尽解释。遗憾的是,它并没有按照您指出的方式解决:Error: <spyOn> : sumNumber is not declared writable or has no setter Usage: spyOn(<object>, <methodName>) 我在其他线程中找到了对我有用的答案:link 无论如何谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-10-10
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多