简体   繁体   English

Angular 测试方法调用未设置变量

[英]Angular test method call is not setting variables

I am trying to learn Jasmine, and I am not sure if I am doing this correctly.我正在尝试学习 Jasmine,但我不确定我这样做是否正确。 When I run this test case, on the line expect(component.roleModal.visible).toBeTrue();当我运行这个测试用例时,行上expect(component.roleModal.visible).toBeTrue(); I get an error saying Expected false to be true .我收到一条错误消息,说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);
  });
});

The function onOpenAdd() is pretty simple: function onOpenAdd()非常简单:

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

Same with open() :open()相同:

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

When the test executes it fails why is this?当测试执行失败时,这是为什么? Am I doing this correctly?我这样做正确吗? I am setting the value visible explicitly to true so why is the test false?我将值visible显式设置为true那么为什么测试为 false?

to make your test work:使您的测试工作:

delete change detection from beforeEach从 beforeEach 中删除更改检测

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

and place your change detection call just after your spy并在您的间谍之后拨打您的变更检测电话

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM