angular - 测试组件方法调用另一个方法

标签 angular jasmine karma-runner

给定这个简单的组件:

import { Component} from '@angular/core';

@Component({
  selector: 'app-component'
})
export class AppComponent {
  foo() {
    this.bar();
  }

  bar() {
    console.log('hello');
  }
}

当我调用 foo 时,为什么下面的测试不会验证调用了 bar

describe('AppComponent', () => {
  let component: AppComponent;

    beforeEach(() => {
    component = new AppComponent();
  }

  it('should foobar', () => {
    component.foo();
    spyOn(component, 'bar');
    expect(component.bar).toHaveBeenCalled();
  })

}

我得到失败的测试:

Expected spy bar to have been called.

最佳答案

您需要在调用该方法之前设置 spy 。 Jasmine 监视包装函数以确定它们何时被调用以及它们被调用的内容。为了捕获信息,必须在调用监视方法之前包装该方法。尝试更改您的测试以匹配以下内容:

it('should foobar', () => {
    spyOn(component, 'bar');
    component.foo();
    expect(component.bar).toHaveBeenCalled();
})

关于angular - 测试组件方法调用另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302114/

相关文章:

requirejs - Squirejs 导致随机测试间歇性失败或根本不运行

css - 隐藏正文(html)以 2/4 的 Angular 滚动

angular - Typescript 错误 - Angular AoT 构建失败 - Node.js + Ionic 移动应用程序

javascript - Angular2/Ionic - 查找数组中的重复项并组织它们

javascript - Jasmine 规范因 Velocity.js 动画和 $.Velocity.mock = true 而失败

jasmine - 在nodejs上使用gulp + babel + jasmine进行测试

html - 如何选择 Angular 6 中的所有复选框?

javascript - Jasmine:测试 toHaveBeenCalledWith(params) 其中 params 是一个对象

node.js - karma : (SystemJS) XHR error (404 Not Found) loading src/node_modules/angular2-jwt/angular2-jwt. js

jquery - AngularJs/在 jasmine 测试中使用 jquery 选择器不起作用