【发布时间】:2019-01-02 01:46:51
【问题描述】:
我正在使用 Angular 5.2.0。我有一个子组件
import { Component } from '@angular/core';
@Component({
template: `<div><\div>`
})
export class ChildComponent {
public childMethod() {
...
}
}
以及一个通过ViewChild访问子组件的父组件
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from 'child.component';
@Component({
template: `<child-component #child><\child-component>`
})
export class ParentComponent {
@ViewChild('child')
public child: ChildComponent;
public parentMethod() {
this.child.childMethod();
}
}
我想要一个单元测试来证明parentMethod 的调用会导致childMethod 的调用。我有以下内容:
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ChildComponent } from './child.component';
import { ParentComponent } from './parent.component';
describe('ParentComponent', () => {
let component: Parentcomponent;
let fixture: ComponentFixture<Parentcomponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ParentComponent, ChildComponent ],
schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TaskListPaginatorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should invoke childMethod when parentMethod is invoked', () => {
const childMethodSpy: jasmine.Spy = spyOn(component.child, 'childMethod');
component.parentMethod();
expect(childMethodSpy).toHaveBeenCalled();
});
});
然而,这不起作用,我得到Error: <spyOn> : could not find an object to spy upon for childMethod()。
此外,这不是单元测试,因为我使用的是真正的 ChildComponent 而不是模拟。我尝试创建一个 MockChildComponent 并将其添加到 declarations 和 export 但我得到了相同的结果。有什么帮助吗?
我知道有类似的帖子,但它们适用于不同版本的 Angular,它们没有帮助。
【问题讨论】:
-
您应该避免使用 NO_ERRORS_SCHEMA。如果您删除它,它会告诉您示例中缺少选择器。使用选择器,您的示例有效。见stackblitz.com/edit/angular-testing-ta7mfv 当然你是对的,嘲笑
ChildComponent是更好的解决方案。
标签: angular unit-testing viewchild testbed