问题描述
我有2个函数,其中一个函数调用另一个函数,另一个函数返回某些内容,但是我无法使测试正常进行.
I have 2 functions where one calls the other and the other returns something, but I cannot get the test to work.
使用expect(x).toHaveBeenCalledWith(someParams);
期望使用间谍,但我不知道如何在同一文件中监视某个函数...
Using expect(x).toHaveBeenCalledWith(someParams);
expects a spy to be used, but I am unaware of how to spy on a function within the same file...
用法:Expect().toHaveBeenCalledWith(... arguments)
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;
}
Example.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 ...
测试的第一行:
In your Example.spec.ts, just add a spyOn(component, 'somethingElse');
as first line of your it('should call somethingElse ...
test :
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作为参数(根据茉莉花文档).
The expect method needs a Spy as parameter when used before a toHaveBeenCalledWith
(as per the Jasmine documentation).
这篇关于调用同一文件中的测试功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!