首页 > 解决方案 > 为使用 routerLink、Spectator 和 Jest 的 Angular 组件编写测试时出现“TypeError:将循环结构转换为 JSON”错误

问题描述

在为我的应用程序设置新的测试平台时,我正在尝试慢慢消除应用程序中复杂模块中的错误。我正在利用观众的路由工厂 api 创建我的测试床(https://github.com/ngneat/spectator#testing-with-routing

describe('LoginComponent', () => {
  let spectator: SpectatorRouting<LoginComponent>;
  let defaultComponentSettings = {
    component: LoginComponent,
    componentMocks: [SessionQuery],
    componentProviders: [
      mockProvider(SessionService, {
        credentials: { email: 'name@example.com' }
      })
    ],
    imports: [...imports, HttpClientTestingModule],
    url: [new UrlSegment('/login', {})]
  };

  let createTargetRedirectUrlComponent = createRoutingFactory({
    ...defaultComponentSettings,
    queryParams: {
      redirectUrl: 'http://any/'
    }
  });

  describe('with target redirectUrl', () => {
    beforeEach(() => {
      spectator = createTargetRedirectUrlComponent();
      spectator.component.mfa_token_view$ = of(false);
      spectator.detectChanges();
    });

    it('should have a sign up link', () => {
      console.log('do we have a form yet', spectator.query('form'));
      expect(spectator.query(byText('Sign up'))).toBeTruthy();
    });
  });
});

现在事情似乎工作正常,直到我[routerLink]在我的模板中添加一个带有指令的锚点<a [routerLink]="['/signup']" class="auth-link">Sign up</a>,这出于某种原因会产生以下错误:

  ● Test suite failed to run

    TypeError: Converting circular structure to JSON
        --> starting at object with constructor 'Object'
        |     property 'element' -> object with constructor 'Object'
        |     property 'publicProviders' -> object with constructor 'Object'
        |     property 'RouterLink_109' -> object with constructor 'Object'
        --- property 'parent' closes the circle
        at stringify (<anonymous>)

      at messageParent (node_modules/jest-runner/node_modules/jest-worker/build/workers/messageParent.js:34:19)

而且我真的不知道如何进一步诊断

标签: angularjestjsrouterlinkspectator

解决方案


啊,找到答案了!

导入列表包括一个本身导入的模块RouterModule,删除了这个修复了错误。


推荐阅读