【问题标题】:Mocking a Directive to Test a Component - Angular 8 with jasmine and Karma模拟指令以测试组件 - Angular 8 与 jasmine 和 Karma
【发布时间】:2020-03-21 13:25:00
【问题描述】:

我尝试为具有一些服务和指令的组件编写单元测试。该指令用于呈现由登录用户和访客用户区分的内容。

“appShowAuthed”默认值为“false”的模拟指令,测试用例通过。但是当我尝试更改该值时,它不会重新渲染视图。

HTML:

<ng-container *appShowAuthed="true">
     <button  id="logout">Logout</button>
</ng-container>

 <ng-container *appShowAuthed="false">
   <button  id="login">Login</button>
</ng-container>

规格文件:

//Passing Case

  it('should show Login button and hide My Orders Button for not logged in user', async () => 
  {
    await fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('#login'))).not.toBeNull();
    expect(fixture.debugElement.query(By.css('#logout'))).toBeNull();
  });



//Failing Case

 it('should show Login button and hide My Orders Button for not logged in user', async () => 
    {
       const datastore = TestBed.get(DataStoreService);
       datastore.isAuthenticated = of(true);

       fixture.detectChanges();
       await fixture.whenStable();
       await fixture.whenRenderingDone();
       expect(fixture.debugElement.query(By.css('#logout'))).not.toBeNull();
       expect(fixture.debugElement.query(By.css('#login'))).toBeNull();
    });

错误:“TypeError: Cannot read property 'startsWith' of undefined”

我已经用最少的代码添加了项目,以便在 gitHub 中重现问题。

Repo Link

请建议我一个更好的方法来解决这个问题。

提前致谢

【问题讨论】:

    标签: angular unit-testing mocking karma-jasmine angular-directive


    【解决方案1】:

    尝试以下方法:

     it('should show Login button and hide My Orders Button for not logged in user', inject(
        [DataStoreService],
        async (injectService: DataStoreService) => {
          fixture.autoDetectChanges(true);
          injectService.isAuthenticated.next(true);
          await fixture.whenStable();
          await fixture.whenRenderingDone();
          expect(
            fixture.debugElement.query(By.css('#logout')),
          ).not.toBeNull();
          expect(fixture.debugElement.query(By.css('#login'))).toBeNull();
        },
      ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2017-09-15
      • 2020-04-10
      • 2018-01-31
      • 2017-01-03
      • 1970-01-01
      • 2019-05-14
      相关资源
      最近更新 更多