gpt4 book ai didi

angular - 在Angular 2+单元测试中导入 stub 文件

转载 作者:行者123 更新时间:2023-12-03 10:07:16 24 4
gpt4 key购买 nike

我的项目有很多实用程序功能,可以执行一些数据转换等。
这些函数不是类,可以在许多实用程序文件中重用。
我是 Angular Testing 的新手。搜索了很长时间,我找不到 stub 已测试文件的方法。这是示例:
/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 stub 。
怎么做?

最佳答案

试试这个:

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

关于angular - 在Angular 2+单元测试中导入 stub 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64221651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com