【问题标题】:Angular Testing: How can i call expectations after a function got executetdAngular 测试:函数执行后如何调用期望值
【发布时间】:2021-09-14 06:43:46
【问题描述】:

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

我目前正在尝试在 http 调用的 .subscribe 中调用期望:

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();

});

问题是期望值是错误的,因为 component.submitFile 在期望之后被调用。我用间谍尝试过,但这不起作用。谁能帮帮我?

编辑:在 submitFile() 方法中包含一个 FileReader,它加载图像并使用其像素。我认为这会导致问题

【问题讨论】:

标签: angular unit-testing http karma-jasmine


【解决方案1】:

您无需从资产中获取文件即可进行测试。您可以在测试中很好地模拟文件。

    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);
    
    
    });

【讨论】:

  • 这是问题的一部分。我需要使用我的资产中的一个文件来测试应用程序是否可以正常使用它。还是谢谢你的回答。
  • 好的,如果是这样,请告诉我 submitFile 方法是否进行了任何 api 调用?如果是这种情况,您也需要模拟它。
  • 不,它不进行任何 api 调用。
  • 但它使用文件阅读器,我认为这是因为函数是异步的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 2020-02-25
相关资源
最近更新 更多