2017-05-23 6 views
0

Jasmine + Sinon을 사용하여 FileReader의 onload를 테스트해야합니다. jasmine을 사용하여 실제 메소드를 호출하는 하나의 메소드 스터 빙

이 기능을 테스트 할 수 있습니다 :
MyObject.prototype.uploadFile = function (file, callback) { 
 
    const fileReader = new FileReader(); 
 

 
    fileReader.onload = event => { 
 
     if (typeof callback === 'function') { 
 
      callback(event); 
 
     } 
 
    }; 
 

 
    fileReader.readAsDataURL(file); 
 
};

그리고 이것은 테스트입니다 :

describe('uploadFile',() => { 
 
     it('should execute the callback',() => { 
 
      let testFunction = jasmine.createSpy(); 
 
      let readData = { 
 
       readAsDataURL:() => { 
 
        this.onload(); 
 
       }, 
 
       onload:() => { 
 
       } 
 
      }; 
 

 
      file = new Blob(['image']); 
 
      sandbox.stub(window, 'FileReader').returns(readData); 
 

 
      component = sandbox.render(BioProfile); 
 
      component.replaceImage(file, testFunction); 
 

 
      expect(testFunction).toHaveBeenCalled(); 
 
     }); 
 
    });

당신이 볼 수 있듯이, 내가되어, readData을에서 스텁 FileReader (비록 제대로 완료되었는지는 모르지만),하지만 스텁이 필요합니다. bed 메서드를 호출하여 FileReader의 실제 메서드 (onload)를 호출하여 테스트 할 수 있습니다.

그럴 수 있습니까?

답변

0

FileReader을 잘못 작성했습니다.

객체 리터럴로

, this는 리터럴 개체가 건설되었다 어떤 컨텍스트.

하지 않는 한 당신은 es6에 소개 된 속기 표기법을 사용합니다.

this.onloadreadAsDataURL에 호출하면 readData 개체에서 onload 함수를 호출하지 않아도됩니다.

그렇게하려면

let readData = { 
    readAsDataURL() { 
     this.onload(); 
    }, 
    onload() {} 
};