Метод done в Jamine просто ждет несколько секунд или делает что-то еще - PullRequest
0 голосов
/ 28 января 2019

Я написал эту спецификацию.Я отправляю событие.Я жду, чтобы событие было получено и обработано.Чтобы ждать, я просто использую 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 голосов
/ 01 февраля 2019

done - это ожидание, но не в том смысле, в котором я думал.Это не timeout, который всегда запускается.Я думаю done действует как контрольная точка в Jasmine.Когда Jasmine видит, что спецификация использует done, он знает, что не может перейти к следующему шагу (скажем, запустить следующую спецификацию или пометить эту спецификацию как завершенную), если не был выполнен фрагмент кода, содержащий done.

Например, jasmine передает эту спецификацию, даже если она потерпит неудачу, поскольку не ожидает вызова 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
  });

Но если я намерен, чтобы Жасмин ожидала асинхронный код в 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.
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...