gpt4 book ai didi

angular2单元测试: cannot read property of componentInstance.方法()未定义

转载 作者:太空狗 更新时间:2023-10-29 17:46:25 27 4
gpt4 key购买 nike

我的组件.spec.ts 类:

这会引发错误:无法读取未定义的属性“ngOnInit”。

let myComponent: MyComponent;
let myService: MyService;

describe('myComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{provide: MyService, useClass: MockMyService} // **--passing Mock service**
]
}).compileComponents()
.then(() => {
myComponent = TestBed.createComponent(MyComponent).componentInstance;
myService = TestBed.get(MyService);
console.log(myService.getData());
});
});

it('should get the mock data', () => {
myComponent.ngOnInit(); //-----------> seems like myComponent is not defined at this place, how to resolve this error
expect(myComponent.data).toBe(DATA_OBJECT);
});
});

下面是我的组件:

@Component({
selector: 'pm-catalogs',
templateUrl: './catalog-list.component.html'
})

export class MyComponent implements OnInit {

public data: IData[];

constructor(private _myService: MyService) {

}

public ngOnInit(): void {
this._myService.getData()
.subscribe(
data => this.data = data
// error => this.errorMessage = <any>error
);
}
}

下面是模拟服务

  export const DATA_OBJECT: IData[] = [
{
'Id': 1,
'value': 'abc'
},
{
'Id': 2,
'value': 'xyz'
}];

@Injectable()
export class MockMyService {
public getData(): Observable<IData[]> {
return Observable.of(DATA_OBJECT);
}
}

我是 Angular2 测试的新手,当 myComponent.ngOnInit() 在我的规范类中调用 myService.getData() 方法时,我希望 myService.getData 返回 DATA_OBJECT请帮助我实现这一目标。

最佳答案

问题是异步beforeEach实现不正确,这会导致竞争条件。

正在做 .compileComponents().then(() => { ... })beforeEach block 导致延迟代码执行 then回调至少一个报价单。 it block 从不等待和访问 myComponent在它有机会被分配之前变量。

当测试没有失败时,这种竞争条件会变得不那么明显并且更加危险。相反,当 beforeEach 时,测试可能会被交叉污染。来自先前测试的结果会影响当前测试中的变量。

.compileComponents()是同步的,除非有带 styleUrls 的组件和 templateUrl (如上例)。在这种情况下,它变为异步,并且 async应该使用助手:

// asynchronous block
beforeEach(async(() => {
TestBed.configureTestingModule({ ... })
.compileComponents();
}));

// synchronous block
beforeEach(() => {
myComponent = ...
});

根据经验, block 应该用 async 包裹起来的 fakeAsync如果 block 有可能是异步的,则提供帮助。

当使用 TestBed 测试组件类时,它们遵循一个生命周期并且它们的钩子(Hook)被自动调用。打电话ngOnInit()不需要手动操作(正如另一个答案所解释的那样),并且会导致两次调用 Hook 。

关于angular2单元测试: cannot read property of componentInstance.方法()未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43973181/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com