как проверить, что мой обработчик событий вызывался, когда FileReader запускает событие загрузки - PullRequest
0 голосов
/ 22 января 2019

В одном из моих методов я использую FileReader для чтения файла. Я предполагаю, что FileReader вызовет событие load, как только файл будет загружен асинхронно.

handleFileSelect(files:ArrayLike<File>){
...
      reader.onload = this.handleReaderLoaded;


      reader.readAsDataURL(file);
    }
  }

Я хочу проверить, что handleReaderLoaded был вызван, но я не могу написать спецификацию для него в Jasmine.

Спецификация, которую я написал до сих пор:

fit('should create a thumbnail of the image file selected', () => {
    let newPracticeQuestionComponent = component;

    let file1 = new File(["foo1"], "foo1.txt");//create file
    spyOn(newPracticeQuestionComponent,'handleReaderLoaded')//this is the load event handler 
    newPracticeQuestionComponent.handleFileSelect([file1]);//handleFileSelect will create FileReader and will also start file load operation 
    expect(newPracticeQuestionComponent.handleReaderLoaded).toHaveBeenCalled();




  });

Спецификация не работает с причиной Expected spy handleReaderLoaded to have been called.. Я предполагаю, что ошибка происходит, потому что загрузка файла асинхронна, и спецификация заканчивается, прежде чем событие загрузки инициируется. Как заставить спецификацию ждать срабатывания события load.

1 Ответ

0 голосов
/ 23 января 2019

Правильный способ, по-видимому, заключается в использовании done метода JAsmine, который, вероятно, указывает Jasmine ждать

  fit('should create a thumbnail of the image file selected', (done) => {
    let newPracticeQuestionComponent = component;
    expect(newPracticeQuestionComponent.consecutiveIdGenerator).toBe(0);
    let file1 = new File(["foo1"], "foo1.txt");
    spyOn(newPracticeQuestionComponent,'handleReaderLoaded').and.callFake(function(event){
      console.log("called fake implementation of handleReaderLoaded ",event);
      expect(event.type).toEqual("load");
      done();
    });
    newPracticeQuestionComponent.handleFileSelect([file1]);    

  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...