Angular:有没有一种方法可以在单元测试中模拟PLATFORM_ID的值?

Pau*_*l M 3 unit-testing guard angular-universal angular

我正在使用Angular Universal。对于在我的服务器或浏览器平台上运行的路由,我的行为有所不同。这是警卫:

export class UniversalShellGuard implements CanActivate {
  private isBrowser: boolean;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    console.log('PLATFORM_ID = ' + platformId);
    this.isBrowser = isPlatformBrowser(this.platformId);
  }

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    return !this.isBrowser;
  }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,警卫正在注入PLATFORM_ID并使用它来确定他是否愿意canActivate()

现在,我想为后卫编写一个简单的单元测试,并执行以下操作:

describe('UniversalShellGuard', () => {
  let guard: UniversalShellGuard;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        UniversalShellGuard,
        // Idea: for now I just want to test the behaviour if I would be on the browser, so I would just use a fixed value for PLATFORM_ID
        { provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID },
      ],
    });

    guard = TestBed.get(UniversalShellGuard);
  });

  it('should deny', () => {
    expect(guard.canActivate()).toBe(false);
  });
});
Run Code Online (Sandbox Code Playgroud)

但是它给出了以下错误:

ERROR in ./src/app/universal-shell.guard.spec.ts
Module not found: Error: Can't resolve '@angular/common/src/platform_id' in '/my-app-path/src/app'
 @ ./src/app/universal-shell.guard.spec.ts 4:0-70 11:50-69
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts
Run Code Online (Sandbox Code Playgroud)

我什至尝试了一种简单而直接的警卫构造,而不使用angular TestBed

it('should deny', () => {
  const guard = new UniversalShellGuard(PLATFORM_BROWSER_ID);
  expect(guard.canActivate()).toBe(false);
});   
Run Code Online (Sandbox Code Playgroud)

同样的错误。

有什么方法可以提供固定值,PLATFORM_ID以便对这样的防护措施进行正确的单元测试?

Pie*_*Duc 7

该值PLATFORM_BROWSER_ID不是公共API的一部分,这就是为什么它从很深的路径导入它的原因,这是不允许的。相反,您可以输入'browser'

{ provide: PLATFORM_ID, useValue: 'browser' },
Run Code Online (Sandbox Code Playgroud)

对于任何其他平台,您可以使用以下值:

export const PLATFORM_BROWSER_ID = 'browser';
export const PLATFORM_SERVER_ID = 'server';
export const PLATFORM_WORKER_APP_ID = 'browserWorkerApp';
export const PLATFORM_WORKER_UI_ID = 'browserWorkerUi';
Run Code Online (Sandbox Code Playgroud)