【发布时间】:2017-10-25 17:27:56
【问题描述】:
我有以下从 Angular 服务中检索数据的组件:
export class MyComponent {
constructor() {
myService.get().then(() => {
console.log('hello from constructor');
});
}
}
然后是我的单元测试:
///////////
it('does something', () => {
console.log('hello from unit test');
});
///////////
不幸的是,这会导致以下日志:
> hello from unit test
> hello from constructor
如何确保构造函数在运行单元测试之前完成?
【问题讨论】:
-
您的问题实际上并不是在测试之前没有调用构造函数,而是关于您希望在测试之前进行服务调用。可能想要隔离它(即从图片中删除构造函数),这样你的问题就更清楚了。 (海事组织)
-
不是
hello from constructor。它是hello from asynchronous code that runs in constructor。一般来说,这样的事情是一种反模式。
标签: angular unit-testing