【问题标题】:Angular test method call is not setting variables角度测试方法调用未设置变量
【发布时间】:2020-06-30 19:22:52
【问题描述】:

我正在尝试学习 Jasmine,但我不确定我是否正确地做到了这一点。当我运行这个测试用例时,在expect(component.roleModal.visible).toBeTrue(); 行我收到一条错误消息Expected false to be true

describe('ManageRolesComponent', () => {
  let component: ManageRolesComponent;
  let fixture: ComponentFixture<ManageRolesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      providers: [HttpClient, HttpHandler],
      declarations: [ManageRolesComponent, RoleModalComponent],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ManageRolesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should open the add modal', () => {
    spyOn(component, 'onOpenAdd').and.callThrough();
    expect(component.roleModal.visible).toBeTrue();
    expect(component.roleModal.state).toBe(ModalRoleState.Add);
  });
});

函数onOpenAdd() 非常简单:

  public onOpenAdd() {
    this.roleModal.state = ModalRoleState.Add;
    this.roleModal.open();
  }

open()相同:

  public open() {
    this.visible = true;
  }

当测试执行失败时,这是为什么?我这样做正确吗?我将值 visible 明确设置为 true 那么为什么测试是假的?

【问题讨论】:

  • 你在你的组件上使用ngOnInit吗?
  • @Roy 是的,我愿意...
  • 我认为您在spyOnexpect 之间缺少组件本身的初始化:component.ngOnInit();
  • 似乎在spyOn 之后我必须明确运行component.onOpenAdd();。我以为这就是.and.callThrough(); 所做的……
  • 不,and.callThrough() 是必需的,间谍仍会跟踪对它的所有调用,但此外它将委托给实际实现。 您也可以直接返回价值。

标签: javascript angular typescript karma-jasmine


【解决方案1】:

让您的测试工作:

从 beforeEach 中删除更改检测

beforeEach(() => {
 fixture = TestBed.createComponent(ManageRolesComponent);
 component = fixture.componentInstance;
 // fixture.detectChanges(); delete this
});

并在您的间谍之后发出更改检测调用

it('should open the add modal', () => {
 spyOn(component, 'onOpenAdd').and.callThrough();
 fixture.detectChanges();
 expect(component.roleModal.visible).toBeTrue();
 expect(component.roleModal.state).toBe(ModalRoleState.Add);
});

【讨论】:

  • 这并不能解决问题。我仍然遇到同样的错误。
猜你喜欢
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2016-08-11
  • 1970-01-01
  • 2014-10-16
相关资源
最近更新 更多