如何解决在 Angular 中测试异步方法
我正在 Angular 中使用 Jasmine 编写单元测试。
export class Component extends AnotherComponent implements OnInit {
@input() public configuration: string;
@input() public data: Data;
private _model: IConfiguration;
public get model(): IConfiguration {
return this._model;
}
constructor(injector: Injector,private _value: Value) {
super(injector);
}
public ngOnInit() {
super.ngOnInit();
}
public async ngOnChanges(changes: SimpleChanges) {
super.ngOnChanges(changes);
if (changes && changes['configuration']) {
this.model = await this.value.doSomething(this.configuration);
}
}
我想测试 ngOnChanges() 方法,特别是里面的 if 。
这是我的测试代码
describe('Component',() => {
let component: Component;
let fixture: ComponentFixture<Component>;
beforeEach(async(() => {
Testbed.configureTestingModule({
imports: [Module,TranslateModule.forRoot()],declarations: [Component]
})
.compileComponents();
}));
beforeEach(() => {
fixture = Testbed.createComponent(Component);
component = fixture.componentInstance;
});
it('Expect model to be not undefined',() => {
const configuration = 'configurationValue';
component.configuration = configuration;
component.data = new SampleData();
fixture.detectCanges();
expect(component.model).not.toBeUndefined();
});
});
我不明白为什么“component.model”仍未定义。我也尝试过fixture.whenStable() 但没有任何改变。
it('model exist',(done) => {
return fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.model).not.toBeUndefined();
done();
});
我做错了什么? 感谢您的帮助。
解决方法
调用 ngOnChanges
的唯一方法是将组件包装在宿主组件中,并更改该宿主组件的属性,这些属性作为输入绑定到您的组件。
您也可以手动调用。
it('Expect model to be not undefined',async (done) => { // add async done here
const configuration = 'configurationValue';
component.configuration = configuration;
component.data = new SampleData();
fixture.detectCanges();
spyOn(value,'doSomething');
await component.ngOnChanges({ configuration: {} });
expect(value.doSomething).toHaveBeenCalledWith({});
expect(component.model).not.toBeUndefined();
});
查看此 link 和其他答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。