簡體   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