[角单位测试]:我如何在单元测试中模拟QueryList(无集成测试)

发布于 2025-01-27 15:23:09 字数 685 浏览 5 评论 0原文

在内容投影方案中,我有以下方案:

// my-component.ts
 @ContentChildren(SelectOption) selectOptions: QueryList<SelectOption>;

...
ngAfterContentInit() {
    this.selectOptions.forEach((selectOption, i) => {
       selectOption.index = i;
    });
}

假设模板具有以下结构:

<ng-content select="select-option"></ng-content>

我试图以下面的方式模拟测试,但是找不到一种“添加”方法,使我可以添加子组件。

// my-component.spec.ts
component.selectOptions = {} as QueryList<SelectOption>;

但是我不知道如何在单元测试方案中添加投影组件(不是集成测试)

In a Content Projection scenario I have the following scenario:

// my-component.ts
 @ContentChildren(SelectOption) selectOptions: QueryList<SelectOption>;

...
ngAfterContentInit() {
    this.selectOptions.forEach((selectOption, i) => {
       selectOption.index = i;
    });
}

Assuming the template has the following structure:

<ng-content select="select-option"></ng-content>

I have tried to mock the test in the following way but I can't find an "add" method that allows me to add the child components.

// my-component.spec.ts
component.selectOptions = {} as QueryList<SelectOption>;

But I don't know how I can add the projected components in a unit test scenario (not an integration test)

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

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

发布评论

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

评论(2

不喜欢何必死缠烂打 2025-02-03 15:23:10

您可以使用 ng-mocks to mock selectoption

beforeEach(() => {
  return TestBed.configureTestingModule({
    declarations: [
      MyComponent,
      MockComponent(SelectOption), // or MockDirective
    ],
  }).compileComponents();
});

it('testing', () => {
  const fixture = MockRender(`
    <my-component>
      <select-option value="1"></select-option>
      <select-option value="2"></select-option>
    </my-component>
  `);

  const component = ngMocks.findInstance(MyComponent);

  expect(component.selectOptions.size).toEqual(2);
  // and other assertions.
});

You can use ng-mocks to mock SelectOption.

beforeEach(() => {
  return TestBed.configureTestingModule({
    declarations: [
      MyComponent,
      MockComponent(SelectOption), // or MockDirective
    ],
  }).compileComponents();
});

it('testing', () => {
  const fixture = MockRender(`
    <my-component>
      <select-option value="1"></select-option>
      <select-option value="2"></select-option>
    </my-component>
  `);

  const component = ngMocks.findInstance(MyComponent);

  expect(component.selectOptions.size).toEqual(2);
  // and other assertions.
});
喜爱纠缠 2025-02-03 15:23:09

使用object.sign()如下:

Object.assign(new QueryList(), {_results: [selectOptionMock1, selectOptionMock2, selectOptionMock3]}) as QueryList<SelectOption>;

Use Object.assign() like below:

Object.assign(new QueryList(), {_results: [selectOptionMock1, selectOptionMock2, selectOptionMock3]}) as QueryList<SelectOption>;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文