Jamine中的完成方法只是等待几秒钟或对其他操作执行

时间:2019-01-28 19:40:25

标签: jasmine

我写了这个规范。我调度了一个事件。我等待事件被接收和处理。等待,我只使用done。让我感到奇怪的是,done只是等待特定的秒数还是做其他事情?

fit('should show dialog box when uploading a file is aborted', (done) => {
    let newComponent = component;
    console.log("component is ",newComponent);

    let file1 = new File(["dd"], "file1",{type:'image/png'});

    spyOn(newComponent,'showDialog');

    let reader = newPracticeQuestionComponent.handleFileSelect([file1]);
    expect(reader).toBeTruthy();
    expect(reader.onabort).toBeTruthy();
    reader.abort();
    expect(newPracticeQuestionComponent.showDialog).toHaveBeenCalled();
    /*done is nothing but wait it seems. It makes the test case wait. This is required as the event
    fired (error) is async. So taht the test case doesn't fiinish before the event is handled, done/wait
    is added.
    */
    done();
  });

1 个答案:

答案 0 :(得分:0)

done正在等待,但并非我认为的那样。它不是始终运行的timeout。我认为done充当Jasmine中的检查点。当Jasmine看到某个规范使用done时,它知道除非包含done的代码分支具有以下条件,否则它无法继续进行下一步(例如运行下一个规范或将该规范标记为完成)。已运行。

例如,茉莉花通过了这个规范,尽管它应该失败,因为它不等待setTimeout被调用。

fit('lets check done',()=>{
    let i=0;
    setTimeout(function(){
      console.log("in timeout");
      expect(i).toBeTruthy();//the spec should fail as i is 0
    },1000);
    //jasmine reaches this point and see there is no expectation so it passes the spec
  });

但是如果我的目的是让Jasmine等待setTimeout中的异步代码,那么我在异步代码中使用done

fit('lets check done',(done)=>{
    let i=0;
    setTimeout(function(){
      console.log("in timeout");
      expect(i).toBeTruthy();//with done, the spec now correctly fails with reason Expected 0 to be truthy.
      done();//this should make jasmine wait for this code leg to be called before startinng the next spec or declaring the verdict of this spec
    },1000);
  });

请注意,done应该在我要检查断言的地方调用。

fit('lets check done',(done)=>{
    let i=0;
    setTimeout(function(){
      console.log("in timeout");
      expect(i).toBeTruthy();//done not used at the right place, so spec will incorrectly ypass again!.
      //done should have been called here as I am asserting in this code leg.
    },1000);
    done();//using done here is not right as this code leg will be hit inn normal execution of it.
  });