模拟指令以测试组件 - Angular 8 with jasmine 和 Karma

Mocking a Directive to Test a Component - Angular 8 with jasmine and Karma

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

"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

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

提前致谢

尝试以下操作:

 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();
    },
  ));