Angular测试:如何在函数被执行后调用期望函数?



我目前在angular中对我的应用程序进行单元测试,并得到了我需要在本地文件上使用http调用的问题。因此,测试的期望在http调用之前和之后被调用,因此它崩溃了。我该如何解决这个问题?

我目前正在尝试在http调用的。subscribe中调用expect:

fit('should get local file and work with it', (done: DoneFn) => {
let file: File;
var blob: Blob;
httpMockService.get('/assets/testFiles/testImage.png', { 
responseType: 'blob' }).subscribe((resp: any) => {

blob = resp
file = new File([blob], 'logo.png', 
{ type: 'image/png', lastModified: Date.now() });
component.submitFile(file); <- get called seecond
expect(component.canBeProgressed).toEqual(true); <- get called first
expect(component.submited).toEqual(false);
done();
});

问题是期望值是错误的,因为组件。submitFile在预期之后被调用。我跟一个间谍试过,但没用。有人能帮我一下吗?

编辑:在submitFile()方法中包含一个FileReader,它加载图像并处理其像素。我认为这就是问题的原因

您不需要从资产中获取要测试的文件。您可以在测试中很好地模拟文件。

fit('should get local file and work with it', () => {
let blob = new Blob([""], { type: 'image/png' });
blob["lastModifiedDate"] = Date.now()
blob["name"] = "test.png";
let mockFile = <File>blob;

component.submitFile(mockFile);

expect(component.canBeProgressed).toEqual(true); 
expect(component.submited).toEqual(false);


});

最新更新