在使用@ ngneat / spectator的Angular 9组件测试中,我遇到了模拟子组件的问题。模拟和传递模拟可以正常工作,但是会在日志中为输入抛出警告(即使它们有效)。
简化的组件如下:
@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'.
有什么想法为什么要记录警告?
答案 0 :(得分:1)
发现了我自己的问题-事实证明createComponentFactory()
必须在beforeEach()
之外被调用。
一旦我将其从beforeEach
块中移出,模拟就开始按预期工作。