2017-09-11 1 views
0

와 타사 모듈을 조롱하는 :내 테스트 대상에서 현재의 수입있어 어떻게 농담

import sharp from 'sharp' 

을 내 동일한 테스트 대상에서 함께 사용 :

내 테스트에서
return sharp(local_read_file) 
    .raw() 
    .toBuffer() 
    .then(outputBuffer => { 

, 나는 날카로운 기능 조롱 아래하고 있어요 :

jest.mock('sharp',() => { 
    raw: jest.fn() 
    toBuffer: jest.fn() 
    then: jest.fn() 
}) 

을하지만 난 받고 있어요 :

return (0, _sharp2.default)(local_read_file). 
          ^
TypeError: (0 , _sharp2.default) is not a function 

Jest를 사용하여 모든 Sharp 모듈 기능을 모의 할 수있는 방법이 있습니까?

답변

3

당신은 이런 식으로 조롱 할 필요가 : 당신이 sharp(local_read_file)를 호출 원인

jest.mock('sharp',() =>() => ({ 
     raw:() => ({ 
      toBuffer:() => ({...}) 
     }) 
    }) 

먼저 당신이 개체 대신 함수를 반환해야합니다. 이 함수 호출은 raw 키를 가진 다른 함수를 보유하고있는 객체를 반환합니다.

모든 기능을 테스트하려면 모든 기능에 대해 스파이를 만들어야합니다. 초기 모의 호출이, 당신은 스파이로 처음을 조롱 할 수 있으며 나중에 모의 객체를 추가 할 수 있듯이 :

jest.mock('sharp',() => jest.fn()) 

import sharp from 'sharp' //this will import the mock 

const then = jest.fn() //create mock `then` function 
const toBuffer = jest.fn({()=> ({then})) //create mock for `toBuffer` function that will return the `then` function 
const raw = jest.fn(()=> ({toBuffer}))//create mock for `raw` function that will return the `toBuffer` function 
sharp.mockImplementation(()=> ({raw})) make `sharp` to return the `raw` function 
+0

을 어떻게 지금 (날카로운) 그것을 callcount 및 인수를 얻을 수 spyon를 사용합니까 ? 실제로 할 수 있을까요? 'const sharpSpy = jest.spyOn ("sharp", "raw") expect (sharpSpy) .toBeCalled(); expect (sharpSpy.mock.calls.length) .toEqual (1);'이것은 내 테스트에서 실패한 것 같습니다. –

+0

이것은 조롱하는 방법이 조금 더 복잡해야합니다. 나는 나의 대답을 업데이트 할 것이다. –

+0

나중에 모형을 추가하여 그 메소드를 사용할 때'TypeError : (0, _sharp2.default) (...). 원시는 함수가 아닙니다. '오류가 발생합니다. –