如何正确地将fakeAsync重建为异步函数

时间:2017-08-04 15:18:39

标签: javascript angular unit-testing jasmine

我有一个在测试fakeAsync中完美的代码但在使用异步时不起作用。

comp.loginStatus在构造函数中返回:

this.subscriptionStatus = this.userService.getStatus().subscribe(status => {
  this.loginStatus = status;
});

在测试fakeAsync工作中:

fit('user inser wrong data - server response 401', fakeAsync(() => {
  expect(comp.loginStatus).toBe(null);
  let object = {
    "timestamp" : 1501857773994,
    "status" : 401,
    "error" : "Unauthorized",
    "exception" : "org.springframework.security.authentication.BadCredentialsException",
    "message" : "Unauthorized",
    "path" : "/auth"
  };
  let spy = spyOn(userService, 'login').and.returnValue(Promise.reject(object));

  comp.loginAction();
  tick();

  fixture.detectChanges();
  expect(comp.loginStatus).toBe(401);
}));

但异步方式不起作用:

fit('user inser wrong data - server response 401', async(() => {
  expect(comp.loginStatus).toBe(null);
  console.log(comp.registerStatus);
  let object = {
    "timestamp" : 1501857773994,
    "status" : 401,
    "error" : "Unauthorized",
    "exception" : "org.springframework.security.authentication.BadCredentialsException",
    "message" : "Unauthorized",
    "path" : "/auth"
  };
  let spy = spyOn(userService, 'login').and.returnValue(Promise.reject(object));

  comp.loginAction();
  fixture.whenStable().then(() => {
    fixture.detectChanges();
    expect(comp.loginStatus).toBe(401);
  });
}));

0 个答案:

没有答案