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

时间:2018-09-05 13:04:37

标签: angular unit-testing guard angular-universal

我正在使用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;
  }
}

如您所见,守卫正在注入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);
  });
});

但是会出现以下错误:

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

我什至尝试了一种简单而直接的后卫结构,而不使用棱角TestBed

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

相同的错误。

有没有办法为PLATFORM_ID提供一个固定值,以便对这种防护措施进行正确的单元测试?

2 个答案:

答案 0 :(得分:4)

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

{ provide: PLATFORM_ID, useValue: 'browser' },

对于其他平台,您可以使用these值:

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';

答案 1 :(得分:0)

另一种测试方法可以是模拟isPlatformBrowser的结果。为此,您应该创建该函数的包装器:

export class UniversalShellGuard implements CanActivate {
    ...
    private isBrowser(): boolean {
        return isPlatformBrowser(this.platformId);
    }
}

然后,使用jasmine Spy,可以模拟isBrowser()方法的返回值:

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

    beforeEach(() => {
      TestBed.configureTestingModule({
        providers: [
          UniversalShellGuard,
          { provide: PLATFORM_ID, useValue: '' },
        ],
      });

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

    it('should deny', () => {
      spyOn(guard, 'isBrowser').and.returnValue(true);
      expect(guard.canActivate()).toBe(false);
    });
});
相关问题