首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在jasmine中正确使用done

无法在jasmine中正确使用done
EN

Stack Overflow用户
提问于 2019-02-01 01:32:36
回答 1查看 18关注 0票数 0

我的html使用ng-template。该模板用于创建缩略图。

代码语言:javascript
复制
 <ng-template #thumbnailTemplate let-option="option">

      <div id="{{option.divId}}"> <!-- top level div of thumbnail. This will have ids thumbnail-1, thumbnail-2 etc.-->
        <img id="{{option.imgId}}" src="{{option.imgSrc}}"> <!-- this will have width, height=80-->
        <a href="#" id="{{option.closeId}}" (click)="deleteThumbnail(option)"></a> <!-- the X button is created using CSS. This will have ids close-button-1, close-button-2. They'll also containn reference to the parent div id (thumbnail-1, thumbnail-2 ) -->
      </div>
    </ng-template>

handleFileSelect创建一个FileReader,为FileReader分配回调,并调用readAsDataURL函数开始读取文件。

代码语言:javascript
复制
handleFileSelect(files:ArrayLike<File>):FileReader|null{
...      let reader:FileReader = new FileReader();


      reader.onload = this.handleReaderLoaded.bind(this);
      reader.onerror = this.handleFileLoadError.bind(this);
      reader.onabort = this.handleFileAbort.bind(this);
      reader.readAsDataURL(file);

  }

异步调用的handleReaderLoaded方法接受加载的文件并对其进行处理。

我想对handleReaderLoaded方法进行单元测试。我这样做的方法是检查两个变量currentImageAttachmentCountthumbnailContainerRef,如果handleReaderLoaded工作正常,它们应该已经更新。我所写的规范如下所示,它可以工作,但我在这里没有使用done函数,我认为它是为了测试jasmine的同步代码而推荐的。

代码语言:javascript
复制
 fit('should upload image if user selects an image', async(() => {
    let newPracticeQuestionComponent = component;
    expect(newPracticeQuestionComponent.currentImageAttachmentCount).toBe(0);
    expect(newPracticeQuestionComponent.thumbnailContainerRef.length).toBe(0);


    let file1 = new File(["foo1"], "foo1.txt");

    let reader = newPracticeQuestionComponent.handleFileSelect([file1]);
    setTimeout(function() {
      console.log("in timeout");
      expect(newPracticeQuestionComponent.currentImageAttachmentCount).toBe(1);
      expect(newPracticeQuestionComponent.thumbnailContainerRef.length).toBe(1);

    }, 2000);


  }));

1)我想使用done方法,但我不知道如何使用它。我如何使用done重写上面的规范。2)由于我可以在没有done方法的情况下进行测试,我想知道done有什么用

EN

回答 1

Stack Overflow用户

发布于 2019-02-01 14:20:46

我错误地认为我的规范在没有done的情况下运行得很好。发生的事情是,Jasmine刚刚完成了it规范,甚至没有等待setTimeout。由于没有要做的断言,规范显示为已通过。

正确的was方法是在异步代码中调用done

代码语言:javascript
复制
 setTimeout(function() {
      console.log("in timeout");
      expect(newPracticeQuestionComponent.currentImageAttachmentCount).toBe(1);
      expect(newPracticeQuestionComponent.thumbnailContainerRef.length).toBe(1);
done(); //without done, jasmine will finish this test spec without checking the assertions in the timeout
    }, 2000);

我认为doneJasmine中扮演着检查点的角色。当Jasmine发现某个规范使用了done时,它知道除非调用了包含done的代码段,否则它不能继续下一步(比如运行下一个规范或将此规范标记为完成)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54466214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档