как смоделировать сбой FileReader - PullRequest
0 голосов
/ 23 января 2019

У меня есть функция, которая создает FileReader. В этой функции я также установил обработчики событий load и error

handleFileSelect(files:ArrayLike<File>){
...
      let reader = new FileReader()
      reader.onload = this.handleReaderLoaded;
      reader.onerror = this.handleReaderError;


      reader.readAsDataURL(file);
    }
  }

Я хочу провести модульное тестирование, чтобы handleFileSelect правильно установил обработчик ошибок и чтобы при возникновении ошибки FileReader вызывался обработчик ошибок (handleReaderError). Но я не могу понять, как заставить FileReader провалиться.

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

fit('should call error handler when file doesn\'t get loaded successfully', (done) => {
    let newPracticeQuestionComponent = component;

    let file1 = new File(["foo1"], "foo1.txt");
    /*
    File reader will load the file asynchronously.
    The `done` method of `Jasmine` makes `Jasmine` wait
    When handleReaderError is called, call a fake function and within it call done
     */
    spyOn(newPracticeQuestionComponent,'handleReaderError').and.callFake(function(event:FileReaderProgressEvent){
      console.log("called fake implementation of handleReaderError ",event);
      expect(event.type).toEqual("abort");
      done();
    });

    newPracticeQuestionComponent.handleFileSelect([file1]);
//I SHOULD SIMULATE FILEREADER ERROR HERE BUT HOW??

  });

1 Ответ

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

Если поведение reader вызывает onerror при сбое readAsDataURL, это должно сделать:

spyOn(newPracticeQuestionComponent.reader, 'readAsDataURL').and.callFake(() => {
    newPracticeQuestionComponent.reader.onerror();
});

Поскольку это будет синхронный вызов, вы можете упростить утверждениев конце теста (после тройки А) вот так:

// Arrange
const newPracticeQuestionComponent = component;
spyOn(newPracticeQuestionComponent, 'handleReaderError');
spyOn(newPracticeQuestionComponent.reader, 'readAsDataURL').and.callFake(() => {
    newPracticeQuestionComponent.reader.onerror();
});
let file1 = new File(["foo1"], "foo1.txt");

// Act
newPracticeQuestionComponent.handleFileSelect([file1]);

// Assert
expect(newPracticeQuestionComponent.handleReaderError).toHaveBeenCalledWith({ type: 'abort' });

Но я не рекомендую ожидать, что параметр передается в функцию, event.type, потому что это спецификациядругого устройства , которое мы в настоящее время не тестируем.(мы тестируем newPracticeQuestionComponent, а не поведение reader, вызывающего ошибку с событием)


Насмешка над поведением reader может быть не лучшим способом.Это зависит от того, что вы хотите проверить против устройства.

В случае, если мы хотим стать чрезвычайно независимыми, newPracticeQuestionComponent не должен ничего знать о поведении reader, даже об ошибке обратного вызова, единственное, что этот аппарат должен знать, это установить обратный вызов onerror, вымогу просто утверждать, что вы правильно установили onerror читателя.

// Arrange
const newPracticeQuestionComponent = component;
spyOn(newPracticeQuestionComponent.reader, 'readAsDataURL');
let file1 = new File(["foo1"], "foo1.txt");

// Act
newPracticeQuestionComponent.handleFileSelect([file1]);

// Assert
expect(newPracticeQuestionComponent.reader.onerror).toBe(newPracticeQuestionComponent.handleReaderError);

Я не мастер в тестировании, но, похоже, плюсы и минусы написание тестов, таких как приведенные выше и приведенные ниже примеры, по многим факторам.

Надеюсь, это поможет:)

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