本文介绍了Angular-茉莉花单元测试的模拟Promise方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public onSubmit(registerData: RegisterDataModel): void {
    this.registrationService.registerWithEmailAndPassword(registerData).then((msg: string[]) =>
      this.router.navigate(['/completeSignUp']).then(() => {
        msg.forEach(singleMessage => this.notificationService.primary(singleMessage));
      }))
      .catch((msg) => msg.forEach(singleMessage => {
        this.notificationService.danger(singleMessage);
      }));
  }

我想测试在我的方法中是否调用了router.navigate.现在,我想模拟我的service.registerWithEmailAndPasswort Promise,但不知何故我无法模拟它.

I want to test if router.navigate is called in my method. Now I want to mock my service.registerWithEmailAndPasswort Promise but somehow I cannot mock it.

//Stubs
const routerStub: Router = jasmine.createSpyObj('Router', ['navigate']);
const registryStub: RegistrationService = jasmine.createSpyObj('RegistrationService', ['registerWithEmailAndPassword']);

单元测试

  it('should navigate on promise - success', () => {
    (<jasmine.Spy>registryStub.registerWithEmailAndPassword).and.callThrough();
    const spy = (<jasmine.Spy>routerStub.navigate);
    component.onSubmit({username: null, email: null, password: null, passwordConfirm: null, termsAndCondition: null});
    expect(spy).toHaveBeenCalledWith(['/completeSignUp']);
  });

出现的错误是:TypeError: Cannot read property 'then' of undefined有人可以嘲笑这项服务吗?

The Error that is appearing is: TypeError: Cannot read property 'then' of undefinedDoes anyone how to proper mock this service?

我也曾尝试嘲笑诺言,例如:

I have also tried to mock the promise like:

    (<jasmine.Spy>registryStub.registerWithEmailAndPassword)
  .and.returnValue(new Promise(() => Promise.resolve()));

但是它仍然让我失望:

Expected spy Router.navigate to have been called with [ [ '/completeSignUp' ] ] but it was never called.

推荐答案

正如Silicon Soul所述,您需要使用返回值明确地模拟router.navigate承诺,否则它将进入Promise.reject()中.通过添加(<jasmine.Spy>routerStub.navigate).and.returnValue(Promise.resolve());单元测试应该可以.最终的单元测试应如下所示:

As silicon Soul mentioned you need definately mock the router.navigate promise with a returnvalue as otherwise it will ent into a Promise.reject(). By adding (<jasmine.Spy>routerStub.navigate).and.returnValue(Promise.resolve()); the unit test should be ok.The final unit test should look like:

  it('should navigate on promise - success', fakeAsync(() => {
    const spy = (<jasmine.Spy>routerStub.navigate).and.returnValue(Promise.resolve());
    (<jasmine.Spy>registryStub.registerWithEmailAndPassword).and.returnValue(Promise.resolve(['test']));
    component.onSubmit({username: 'test', email: 'test', password: 'test', passwordConfirm: 'test', termsAndCondition: true});

    tick();
    expect(spy).toHaveBeenCalledWith(['/completeSignUp']);
  }));

这篇关于Angular-茉莉花单元测试的模拟Promise方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:43