javascript - 无法让 spyOn 测试正常工作 - Angular

标签 javascript angular typescript testing karma-runner

由于某种原因我无法让我的测试工作并且它不断抛出错误:

Expected spy on isCurrentStatus to equal true.

被调用的函数只是评估传入的变量是否等于当前持有的 status 属性,并返回 true 或 false。没什么大不了的……

测试

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() 部分,现在返回:

expected undefined to equal true

最佳答案

您可以在该函数上创建一个 spyOn 并检查它返回的不同值:

spyOn(component, 'isCurrentStatus').and.callThrough();
component.event = failedEvent;
const statusResult = component.isCurrentStatus('failed');
expect(statusResult).toBeTruthy();

关于javascript - 无法让 spyOn 测试正常工作 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52151981/

相关文章:

angular - 如何为 *.spec.ts 文件使用不同的 tslint.json

javascript - Backbone : the best way to communicate entities

javascript - angularjs 为特定类型的所有 html 元素赋予自己的范围

html - 切换 JSON 对象值

javascript - 光标在 ngModelChange Angular/Typescript 上结束时出现问题

数据更改时 Angular2 组件不渲染

typescript - 我们可以在 typescript 中访问另一个类中的私有(private)变量吗

javascript - 带有 ScrollView 的 KeyboardAvoidingView 在 react-native 或 expo 中不起作用

javascript - 如何使用 pdf.js

javascript - TypeScript - 类型 'id' 上不存在属性 'Node'