代码之家  ›  专栏  ›  技术社区  ›  MarcoLe

茉莉花单元试验的角模拟承诺法

  •  8
  • MarcoLe  · 技术社区  · 6 年前

    试验方法

      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 答应我,但我不能嘲笑。

    我的规范文件

    //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 有谁能恰当地模仿这项服务吗?

    编辑

    我也曾试图嘲弄这个承诺,比如:

        (<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.
    
    2 回复  |  直到 6 年前
        1
  •  8
  •   user9353955user9353955    6 年前

    正如silicon Soul所说,你需要明确地嘲笑 router.navigate 有回报价值的承诺,否则它将成为 Promise.reject() . 通过添加 (<jasmine.Spy>routerStub.navigate).and.returnValue(Promise.resolve()); 单元测试应该没问题。 最后的单元测试应该是:

      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']);
      }));
    
        2
  •  1
  •   SiliconSoul    6 年前

    您将得到错误,因为registerWithEmailAndPassword间谍没有返回承诺。你可以用callFake来回信:

    (<jasmine.Spy>registryStub.registerWithEmailAndPassword).and.callFake(() => Promise.resolve([]));
    

    而且,承诺是异步的,所以您可能应该使用 fakeAsync 测试并勾选,或超时或返回对象 然后 方法而不是承诺。