无法使 spyOn 测试正常工作- Angular
Cannot get spyOn test to work properly- Angular
由于某种原因我无法让我的测试工作并且它一直在抛出错误:
Expected spy on isCurrentStatus to equal true.
被调用的函数只是评估传入的变量是否等于当前持有的 status
属性,以及 returns 是真还是假。没什么大不了的...
测试
it('should return true if current status = status passed in', () => {
const statusSpy = spyOn(component, 'isCurrentStatus');
component.event = failedEvent;
component.isCurrentStatus('failed');
expect(statusSpy).toEqual(true);
})
组件
event: MyEvent;
isCurrentStatus(status: string): boolean {
return this.event.status === status;
}
更新
我刚刚将 spyOn
移到了 beforeEach()
部分,现在 returns:
expected undefined
to equal true
试试这个来测试返回值
expect(component.isCurrentStatus('failed')).toEqual(true);
你可以检查方法是否被调用
const statusSpy = spyOn(component, 'isCurrentStatus').and.callThrough();
...
expect(statusSpy).toHaveBeenCalledTimes(1);
你可以检查参数
expect(statusSpy).toHaveBeenCalledWith('failed')
您可以在该函数上创建一个 spyOn 并以不同的方式检查它的值 returns:
spyOn(component, 'isCurrentStatus').and.callThrough();
component.event = failedEvent;
const statusResult = component.isCurrentStatus('failed');
expect(statusResult).toBeTruthy();
Expected spy on isCurrentStatus to equal true.
因为 spyOn
实际上创建了一个 spy
。你尝试了 expect(Spy).toEqual(Boolean);
之类的东西,所以你得到了这样的错误。
expected undefined to equal true
- 因为 beforeEach()
的作用域不在你的测试函数中 (it()
) 作用域
因为你想测试 returned 值 - 你不需要在这里监视。只需调用函数并检查其结果。
当您需要测试的不是 return 值而是其他东西时,就需要 Spy - 例如,它是注入依赖项的函数,但您需要确信它已被调用。所以,你创造了一个间谍。或者:您需要检查函数被调用了多少次,传递了哪些参数等。或者您何时需要模拟其行为。
由于某种原因我无法让我的测试工作并且它一直在抛出错误:
Expected spy on isCurrentStatus to equal true.
被调用的函数只是评估传入的变量是否等于当前持有的 status
属性,以及 returns 是真还是假。没什么大不了的...
测试
it('should return true if current status = status passed in', () => {
const statusSpy = spyOn(component, 'isCurrentStatus');
component.event = failedEvent;
component.isCurrentStatus('failed');
expect(statusSpy).toEqual(true);
})
组件
event: MyEvent;
isCurrentStatus(status: string): boolean {
return this.event.status === status;
}
更新
我刚刚将 spyOn
移到了 beforeEach()
部分,现在 returns:
expected
undefined
to equaltrue
试试这个来测试返回值
expect(component.isCurrentStatus('failed')).toEqual(true);
你可以检查方法是否被调用
const statusSpy = spyOn(component, 'isCurrentStatus').and.callThrough();
...
expect(statusSpy).toHaveBeenCalledTimes(1);
你可以检查参数
expect(statusSpy).toHaveBeenCalledWith('failed')
您可以在该函数上创建一个 spyOn 并以不同的方式检查它的值 returns:
spyOn(component, 'isCurrentStatus').and.callThrough();
component.event = failedEvent;
const statusResult = component.isCurrentStatus('failed');
expect(statusResult).toBeTruthy();
Expected spy on isCurrentStatus to equal true.
因为 spyOn
实际上创建了一个 spy
。你尝试了 expect(Spy).toEqual(Boolean);
之类的东西,所以你得到了这样的错误。
expected undefined to equal true
- 因为 beforeEach()
的作用域不在你的测试函数中 (it()
) 作用域
因为你想测试 returned 值 - 你不需要在这里监视。只需调用函数并检查其结果。
当您需要测试的不是 return 值而是其他东西时,就需要 Spy - 例如,它是注入依赖项的函数,但您需要确信它已被调用。所以,你创造了一个间谍。或者:您需要检查函数被调用了多少次,传递了哪些参数等。或者您何时需要模拟其行为。