Angular 2问题与异步测试

时间:2017-03-23 20:34:25

标签: angular jasmine angular2-testing

我在组件中有以下方法:

onSignup() {
    if (this.form.valid) {
      let email = this.form.value.email;
      let password = this.form.value.password;
      this.usersService.signup(email, password)
        .then(() => {
          this.router.navigate(['/app/recipes']);
        })
        .catch(err => {
          console.log('2')
          this.mdlSnackbarService.showToast(err);
        });
    }
  }

以下单元测试:

it('#onSignup should show error on error', async(() => {
    spyOn(fixture.debugElement.injector.get(UsersService), 'signup')
      .and.returnValue(Promise.reject('some error'));

    component.form.setValue({'email': 'mail@mail.com', 'password': '123456'});

    console.log('1')
    component.onSignup();

    fixture.whenStable().then(() => {
      console.log('3')
      expect(snackbar.showToast).toHaveBeenCalled();
    })
  }));

我用:

模拟了snackBarService
snackbar = { showToast: jasmine.createSpy('showToast').and.callFake((str)=>console.log(str)) };

检查输出,我可以看到如何正确调用模拟,但是,同步的东西不太正确:

LOG: '1'
Chrome 56.0.2924 (Mac OS X 10.10.5): Executed 0 of 7 SUCCESS (0 secs / 0 secs)
LOG: '3'
Chrome 56.0.2924 (Mac OS X 10.10.5): Executed 0 of 7 SUCCESS (0 secs / 0 secs)
LOG: '2'
Chrome 56.0.2924 (Mac OS X 10.10.5): Executed 0 of 7 SUCCESS (0 secs / 0 secs)
LOG: 'some error'

似乎在调用方法之前执行了对被调用方法的检查。然后它以Expected spy showToast to have been called.失败。

有谁可以指出我在这里做错了什么?

0 个答案:

没有答案