gpt4 book ai didi

javascript - 调用同一文件中的测试函数

转载 作者:行者123 更新时间:2023-11-28 20:36:42 25 4
gpt4 key购买 nike

我有 2 个函数,一个调用另一个,另一个返回一些东西,但我无法让测试工作。

使用 expect(x).toHaveBeenCalledWith(someParams); 期望使用 spy ,但我不知道如何监视同一文件中的函数...

Error: : Expected a spy, but got Function.

Usage: expect().toHaveBeenCalledWith(...arguments)

Example.ts

doSomething(word: string) {
if (word === 'hello') {
return this.somethingElse(1);
}
return;
}

somethingElse(num: number) {
var x = { "num": num };
return x;
}

示例.spec.ts

fake = {"num": "1"};

it('should call somethingElse', () => {
component.doSomething('hello');
expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
expect(component.somethingElse(1)).toEqual(fake);
});

最佳答案

在您的 Example.spec.ts 中,只需添加一个 spyOn(component, 'somethingElse'); 作为您的第一行 it('should call somethingElse ... 测试:

fake = {"num": "1"};

it('should call somethingElse', () => {
// Add the line below.
spyOn(component, 'somethingElse');
component.doSomething('hello');
expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
expect(component.somethingElse(1)).toEqual(fake);
});

当在 toHaveBeenCalledWith 之前使用时,expect 方法需要一个 Spy 作为参数(根据 Jasmine documentation )。

关于javascript - 调用同一文件中的测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073418/

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