繁体   English   中英

Angular 单元测试在子组件上模拟父组件

[英]Angular unit test mock parent component on child component

我正在尝试测试子组件,但它的主要功能需要父组件。

如何使用“模拟”父级测试子组件?

(使用 Jest,Angular 14,TypeScript)

parent.component.ts

@Component({...})
export class ParentComponent {
    onChildClicked(child: ChildComponent) {
        // ...
    }
}

child.component.ts

@Component({...})
export class ChildComponent {
  constructor(private parent: ParentComponent) {}

  onClick() {
    this.parent.onChildClicked(this);
  }
}

child.component.spec.ts

describe("ChildComponent", () => {
  it("should be rendered", async () => {
    const { container } = await render(ChildComponent, {
      declarations: [ParentComponent],
    });
    expect(container).toBeTruthy();
  });
});

page.component.html

<app-parent>
  <app-child></app-child>
</app-parent>

测试 output:

ChildComponent › should be rendered

    NullInjectorError: R3InjectorError(DynamicTestModule)[ParentComponent -> ParentComponent]:
      NullInjectorError: No provider for ParentComponent!

我找到了解决方案。 使父组件可用作子组件的提供者。

child.component.spec.ts


describe("ChildComponent", () => {
  it("should be rendered", async () => {
    const { container } = await render(ChildComponent, {
      declarations: [ParentComponent],
      providers: [ParentComponent]
    });
    expect(container).toBeTruthy();
  });
});

为什么你在子组件中像这样调用父 function ,并且你不应该在子组件中注入父组件作为依赖项。

如果要根据子组件内的某些事件单击调用父 function,则使用@Output()事件发射器。

像下面

父组件

 onChildClicked(value) {
            console.log(value);
 }





<app-parent>
  <app-child (childClicked)='onChildClicked($event)'></app-child>
</app-parent>

子组件

@Output() childClicked = new EventEmitter()

onClick() {  
        this.childClicked.emit(value_you_want_to_pass);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM