NgMocks: 无法为canActivate守卫编写测试

huangapple go评论79阅读模式
英文:

NgMocks: cannot write test for canActivate guard

问题

我正在实现一个简单的canActivate守卫的测试。请看下面的代码:

// 守卫
export const hasGraphResultsCanActiveGuard: CanActivateFn = (
  route: ActivatedRouteSnapshot,
  routerState: RouterStateSnapshot
) => {
  return inject(Store)
    .select(selectGraphResults)
    .pipe(
      map((results) => {
        return results.length > 0;
      }),
      tap((hasResults) => {
        if (!hasResults) {
          inject(Router).navigate(['/app/map']);
        }
      })
    );
};

// 模块中使用的路由
const routes: Routes = [
  {
    path: 'analysis',
    component: AnalysisComponent,
    canActivate: [hasGraphResultsCanActiveGuard],
  },
  {
    path: '**',
    pathMatch: 'full',
    redirectTo: 'analysis',
  },
];

// 测试
describe('HasGraphResultsGuard', () => {
  beforeEach(() => {
    return (
      MockBuilder(
        [
          RouterModule,
          RouterTestingModule.withRoutes([]),
          NG_MOCKS_ROOT_PROVIDERS,
        ],
        DisruptionPageModule
      )
        .exclude(NG_MOCKS_GUARDS)
        .keep(hasGraphResultsCanActiveGuard)
        .provide(
          provideMockStore({
            initialState: {
              graph: cloneDeep(initialGraphState),
            },
          })
        )
    );
  });

  it('重定向到/app/map', fakeAsync(() => {
    const fixture = MockRender(RouterOutlet, {});
    const router = ngMocks.get(Router);
    const location = ngMocks.get(Location);

    // 初始化导航
    if (fixture.ngZone) {
      fixture.ngZone.run(() => router.initialNavigation());
      tick();
    }

    // 初始状态没有图表结果,所以应该重定向
    expect(location.path()).toEqual('/app/map');
  }));
});

除非我漏掉了什么,否则我认为我已经按照文档的建议完全实现了测试。以下是我收到的错误消息:

错误:MockBuilder找到了一个缺少的依赖项:hasGraphResultsCanActiveGuard。这意味着没有模块提供它。请使用“export”标志如果您想显式添加它。https://ng-mocks.sudo.eu/api/MockBuilder#export-flag

我尝试添加了导出标志,然后它说无法解析参数。

这个守卫在我的应用程序中按预期工作,但我无法在测试中正确连接事物。我是否漏掉了什么,还是文档不完整?

英文:

I'm implementing tests for a simple canActivate guard. See below:

// guard
export const hasGraphResultsCanActiveGuard: CanActivateFn = (
  route: ActivatedRouteSnapshot,
  routerState: RouterStateSnapshot
) => {
  return inject(Store)
    .select(selectGraphResults)
    .pipe(
      map((results) => {
        return results.length > 0;
      }),
      tap((hasResults) => {
        if (!hasResults) {
          inject(Router).navigate(['/app/map']);
        }
      })
    );
};

// routes in the module where its used
const routes: Routes = [
  {
    path: 'analysis',
    component: AnalysisComponent,
    canActivate: [hasGraphResultsCanActiveGuard],
  },
  {
    path: '**',
    pathMatch: 'full',
    redirectTo: 'analysis',
  },
];

// Test
describe('HasGraphResultsGuard', () => {
  beforeEach(() => {
    return (
      MockBuilder(
        [
          RouterModule,
          RouterTestingModule.withRoutes([]),
          NG_MOCKS_ROOT_PROVIDERS,
        ],
        DisruptionPageModule
      )
        .exclude(NG_MOCKS_GUARDS)
        .keep(hasGraphResultsCanActiveGuard)
        .provide(
          provideMockStore({
            initialState: {
              graph: cloneDeep(initialGraphState),
            },
          })
        )
    );
  });

  it('Redirects to /app/map', fakeAsync(() => {
    const fixture = MockRender(RouterOutlet, {});
    const router = ngMocks.get(Router);
    const location = ngMocks.get(Location);

    // Initialize navigation
    if (fixture.ngZone) {
      fixture.ngZone.run(() => router.initialNavigation());
      tick();
    }

    // The initial state has no graph results so it should redirect
    expect(location.path()).toEqual('/app/map');
  }));
});

Unless I've missed something I believe I've implemented the test exactly as the docs suggest. Heres the error I get:

> Error: MockBuilder has found a missing dependency: hasGraphResultsCanActiveGuard. It means no module provides it. Please, use the "export" flag if you want to add it explicitly. https://ng-mocks.sudo.eu/api/MockBuilder#export-flag

I've tried adding the export flag and then it says it cant resolve the parameters.

The guard works as intended in my app but I cant connect things correctly in the test. Am I missing something or are the docs incomplete?

答案1

得分: 1

我认为ng-mocks更新到14.11.0解决了相同的问题。

英文:

had the same issue, i think a ng-mocks update to 14.11.0 solved it

huangapple
  • 本文由 发表于 2023年6月29日 00:33:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定