use*_*014 43 javascript unit-testing jasmine
是否可以在类私有方法上使用Jasmine单元测试框架的spyon方法?
文档给出了这个例子,但这可以灵活用于私有函数吗?
describe("Person", function() {
it("calls the sayHello() function", function() {
var fakePerson = new Person();
spyOn(fakePerson, "sayHello");
fakePerson.helloSomeone("world");
expect(fakePerson.sayHello).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
提前致谢
Lui*_*yfe 90
只需在spyon()函数中添加一个通用参数<any>:
spyOn<any>(fakePerson, 'sayHello');
Run Code Online (Sandbox Code Playgroud)
它完美地工作!
ome*_*mer 20
spyOn<any>(fakePerson, 'sayHello');
expect(fakePerson['sayHello']).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)
通过添加<any>
到 spyOn,您可以将其从打字稿类型检查中删除。您还需要使用数组索引符号来访问测试中的私有方法(sayHello)
A-S*_*ani 16
假设sayHello(text: string)
是一个私有方法。您可以使用以下代码:
// Create a spy on it using "any"
spyOn<any>(fakePerson, 'sayHello').and.callThrough();
// To access the private (or protected) method use [ ] operator:
expect(fakeperson['sayHello']).toHaveBeenCalledWith('your-params-to-sayhello');
Run Code Online (Sandbox Code Playgroud)
any
.[]
运算符。spyOn(fakePerson, <never>'sayHello');
Run Code Online (Sandbox Code Playgroud)
spyOn(fakePerson, <keyof Person>'sayHello');
Run Code Online (Sandbox Code Playgroud)
两者都会消除类型错误并且不会干扰 TSLint 的no-any
规则。
如果您为对象使用 Typescript,则该功能并不是真正私有的。
您只需要保存从spyOn
调用返回的值,然后查询它的calls
属性。
最后这段代码应该适合你(至少它对我有用):
describe("Person", function() {
it("calls the sayHello() function", function() {
var fakePerson = new Person();
// save the return value:
var spiedFunction = spyOn<any>(fakePerson, "sayHello");
fakePerson.helloSomeone("world");
// query the calls property:
expect(spiedFunction.calls.any()).toBeFalsy();
});
});
Run Code Online (Sandbox Code Playgroud)
小智 5
就我而言(打字稿):
jest.spyOn<any, string>(authService, 'isTokenActual')
Run Code Online (Sandbox Code Playgroud)
或模拟结果:
jest.spyOn<any, string>(authService, 'isTokenActual').mockImplementation(() => {
return false;
});
Run Code Online (Sandbox Code Playgroud)
And*_*rle -2
没有原因,您无法访问实例上下文之外的私有函数。
顺便说一句,监视你想要测试的对象并不是一个好主意。当您测试您想要测试的类中是否调用了特定方法时,它什么也没说。假设您编写了测试并通过了,两周后您重构了函数中的一些内容并添加了一个错误。所以你的测试仍然是绿色的,因为你调用了函数。乙
当您使用依赖注入时,间谍非常有用,其中所有外部依赖项都由构造函数传递,而不是在您的类中创建。假设您有一个需要 dom 元素的类。通常,您会在类中使用 jquery 选择器来获取此元素。但是你想如何测试该元素是否完成了某些操作呢?当然你可以将它添加到你的测试页面 html 中。但您也可以在构造函数中传递元素来调用您的类。这样做,您可以使用间谍来检查您的类是否按照您的预期与该元素交互。