在Angular 9组件测试中,我遇到了一个使用@ngnate/viewer模拟子组件的问题。mock的模拟和传递很好,但它会在日志中为输入抛出警告(即使它们是有效的(。
简化的组件如下所示:
@Component({
selector: 'child',
template: '<h2>{{someInput}}</h2>'
})
export class ChildComponent {
@Input() someInput: string;
}
@Component({
selector: 'parent',
template: '<child [someInput]="inputVal"></child>'
})
export class ParentComponent {
public inputVal = 'hello';
}
现在观众测试
import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { MockComponent } from 'ng-mocks';
...
describe('ParentComponent', () => {
let spectator: Spectator<ParentComponent>;
let createComponent: SpectatorFactory<ParentComponent>;
beforeEach(() => {
createComponent = createComponentFactory({
component: ParentComponent,
declarations: [MockComponent(ChildComponent)]
});
spectator = createComponent();
});
describe('example', () => {
it('should set the input', () => {
expect(spectator.query(ChildComponent).someInput).toEqual('hello');
});
});
});
测试运行良好并通过。然而,日志会打印警告:
console.warn
Can't bind to 'someInput' since it isn't a known property of 'child'.
知道它为什么会记录警告吗?
发现我自己的问题-原来createComponentFactory()
必须在beforeEach()
之外调用。
一旦我将其移出beforeEach
块,mock就开始按预期工作。