模拟组件仍然包括实际组件

发布于 2025-02-09 07:16:30 字数 829 浏览 1 评论 0原文

在我的单元测试中,我正在执行以下操作(通过 @ngneat/coptator):

    const createComponent = createComponentFactory({
        component: AppComponent,
        detectChanges: false,
        declarations: MockComponents(IgxToastComponent, NgxUiLoaderComponent),
        imports: [
            CommonModule, IgxToastModule, RouterTestingModule, NgxUiLoaderModule,
            MockComponent(HeaderComponent)
        ],
        mocks: [ToasterService]
    })

HeaderComponent是独立组件,因此根据NG-Mock网站上的说明,我将其包含在导入中。但是,当我运行测试时,我会从HeaderComponent的构建中遇到错误,因为它包含了此组件不使用/模拟的其他服务。我的理解是,通过使用MockComponent它应该已经伪造了组件,即使HTML仍然具有< app-header>,它实际上并没有尝试加载。 HeaderComponent

我应该做不同的事情吗?

我正在使用NG Mocks 14.0.1

In my unit test I'm doing the following (via @ngneat/spectator):

    const createComponent = createComponentFactory({
        component: AppComponent,
        detectChanges: false,
        declarations: MockComponents(IgxToastComponent, NgxUiLoaderComponent),
        imports: [
            CommonModule, IgxToastModule, RouterTestingModule, NgxUiLoaderModule,
            MockComponent(HeaderComponent)
        ],
        mocks: [ToasterService]
    })

The HeaderComponent is a standalone component and so per the instructions on the ng-mock site I included it in the imports. When I run my tests though, I'm getting errors from the construction of the HeaderComponent since it include other services that this component doesn't use/mock. My understanding is that by using MockComponent it should have faked out the component so that even though the html still has <app-header> it doesn't actually try to load the HeaderComponent.

Am I supposed to be doing something differently?

I'm using ng-mocks 14.0.1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原来是傀儡 2025-02-16 07:16:30

因为您的组件是独立的,所以您需要使用 ocalbuilder 。它将保留AppComponent,而其导入将被模拟:

// building TestingModule definition
const dependencies = MockBuilder(
  [AppComponent, RouterTestingModule],
).build();

const createComponent = createComponentFactory({
  component: AppComponent,
  detectChanges: false,
  mocks: [ToasterService],

  // adding dependencies where AppComponent is kept,
  // and its imports are mocks
  ...dependencies,
});

Because your components are standalone, you need to use MockBuilder. It will keep AppComponent as it is, whereas its imports will be mocked:

// building TestingModule definition
const dependencies = MockBuilder(
  [AppComponent, RouterTestingModule],
).build();

const createComponent = createComponentFactory({
  component: AppComponent,
  detectChanges: false,
  mocks: [ToasterService],

  // adding dependencies where AppComponent is kept,
  // and its imports are mocks
  ...dependencies,
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文