gpt4 book ai didi

Angular:有没有办法在单元测试中模拟 PLATFORM_ID 的值?

转载 作者:行者123 更新时间:2023-12-02 19:04:48 25 4
gpt4 key购买 nike

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

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

我什至尝试了一种简单直接的防护结构,而不使用 Angular TestBed:

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

同样的错误。

是否有任何方法可以为 PLATFORM_ID 提供固定值,以便正确地对此类防护进行单元测试?

最佳答案

PLATFORM_BROWSER_ID不是公共(public)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';

关于Angular:有没有办法在单元测试中模拟 PLATFORM_ID 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52185873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com