Angular 如何在Jasmine中编写切换布尔值的两个测试用例

Angular 如何在Jasmine中编写切换布尔值的两个测试用例,angular,jasmine,Angular,Jasmine,需要为切换一个布尔值的函数编写单元测试用例 这是给Angular 6和Jasmine的。该函数是基本函数,工作正常。然而,我对Jasmine(和单元测试用例)还不熟悉,我的测试用例失败了 // This works as expected toggle() { this.expand = !this.expand; } 预期的布尔值应该与当前运行函数之前的值相反。我认为您可能需要使用组件实例 // These test cases fail it('should toggle', ()

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

这是给Angular 6和Jasmine的。该函数是基本函数,工作正常。然而,我对Jasmine(和单元测试用例)还不熟悉,我的测试用例失败了

// This works as expected
toggle() {
   this.expand = !this.expand;
}

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

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

// 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);
});

这个切换函数是在组件内部还是在服务或全局函数内部?@Erbsenkoenig问得好。该切换函数位于角度组件内部,当组件初始化时,我将布尔值设置为false:expand:boolean=false;在您的测试中,您将无法使用
this
访问expand属性,而是使用fixture.componentInstance访问组件中的所有内容。通常在从cli生成的测试中,fixture.componentInstance已分配给常量
组件
// 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);
});