测试功能路由解析器

ajp*_*p11 3 jestjs angular

基于类的路由解析器最近在 Angular 中已被弃用,取而代之的是功能解析器。请参阅此处的文档。

有人有单元测试这些功能解析器的示例吗?

我在 Angular 文档中没有找到任何示例,并且 Angular 测试环境很难配置。例如,一个单元如何测试文档中的示例函数?

export const heroResolver: ResolveFn<Hero> =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
      return inject(HeroService).getHero(route.paramMap.get('id')!);
    };
Run Code Online (Sandbox Code Playgroud)

我使用的解析器与此基本相同,因为它调用某些服务来通过 ID 获取实体。当尝试在 Jest 中配置调用解析器时,出现以下错误:

NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. Find more at https://angular.io/errors/NG0203
Run Code Online (Sandbox Code Playgroud)

Nil*_*gat 6

这是我与自己斗争的一个问题,直到我找到解决方案才放手,我很高兴现在向您展示;)

我在 Netanel Basel 撰写的这篇题为“在 Angular 中测试 DI 函数”的优秀文章中找到了我正在寻找的内容:https ://netbasal.com/testing-di-functions-in-angular-37a5e7ed75f9 。

你想要的 API 已经TestBed.runInInjectionContext()在 Angular 中发布了15.1,所以是最近的东西。

假设 getHero() 返回一个 observable,解决方案如下:

it('should call getHero()', (done) => {
    TestBed.runInInjectionContext(() => heroResolver(routeMock, stateMock)).subscribe(() => {            
        expect(heroServiceMock.getHero).toHaveBeenCalledWith(routeMock.paramMap['id']);
        done();
    });
});
Run Code Online (Sandbox Code Playgroud)

我没有测试getHero()这里返回的内容,这可能是您想要针对您的具体情况添加的内容。routeMockstateMock您必须为测试用例设置和填充的模拟。

希望这有帮助!