【问题标题】:How to write two test cases for toggling boolean value in Jasmine如何编写两个测试用例在 Jasmine 中切换布尔值
【发布时间】:2019-05-02 17:55:10
【问题描述】:

需要为切换一个布尔值的函数编写单元测试用例

这适用于 Angular 6 和 Jasmine。该功能是基本的并且按预期工作。但是,我是 Jasmine(和单元测试用例)的新手,我的测试用例失败了。

// This works as expected
toggle() {
   this.expand = !this.expand;
}
// These test cases fail
it('should toggle', () => {
  this.expand = false;
  component.toggle();
  expect(this.expand).toBe(true);
});

it('should toggle', () => {
  this.expand = true;
  component.toggle();
  expect(this.expand).toBe(false);
});

预期的布尔值应该与运行函数之前的当前值相反。

【问题讨论】:

  • 这个切换函数是在组件内部还是在服务内部还是全局函数内部?
  • @Erbsenkoenig 好问题。此切换功能位于 Angular 组件内部,当组件初始化时,我将布尔值设置为 false:expand: Boolean = false;
  • 那么在您的测试中,您将无法使用 this 访问 expand 属性,而是使用 fixture.componentInstance 从您的组件中访问所有内容。通常在 cli 生成的测试中,fixture.componentInstance 已经分配给常量component

标签: angular jasmine


【解决方案1】:

我认为您可能需要使用组件实例

// These test cases fail
it('should toggle', () => {
  component.expand = false;
  component.toggle();
  expect(component.expand).toBe(true);
});

it('should toggle', () => {
  component.expand = true;
  component.toggle();
  expect(component.expand).toBe(false);
});

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2021-10-15
    相关资源
    最近更新 更多