2016-11-23 2 views
11

나는 함수 호출을 모의하려고하고있다. 그리고 한 번 안에 다른 함수를 호출하려고한다.Jest - 함수 호출 조롱

myFunctions.test.js

import { resetModal } from '../myFunctions.js'; 

describe('resetModal',() => { 
    it('calls the clearSomethingInModal function',() => { 
    const clearSomethingInModal = jest.fn(); 
    resetCreationModal(); 
    expect(clearSomethingInModal.mock.calls.length).toBe(1); 
    }) 
}) 

myFunctions.js

export resetModal() { 
    clearSomethingInModal() 
} 

그러나 농담 출력이 호출되지 않았 음을 말한다

. 누구나 최선을 다해 제안 할 수 있다면, 나는 매우 감사 할 것입니다.

답변

16

clearSomethingInModal을 테스트 파일의 컨텍스트에서만 모의하기 때문에 접근 방법이 작동하지 않으므로 myFunction.js에있는 clearSomethingInModal은 여전히 ​​원본입니다. 요점은 myFunction.js에서 직접 생성 된 것을 조롱 할 수 없다는 것입니다. 당신이 조롱 할 수있는 유일한 방법은 테스트에서 그들을 호출 할 때 함수에 통과 import clearSomethingInModal from 'clearSomethingInModal'

  • 콜백처럼 당신이 myFunction.js에 가져

    1. 모듈이다

    이는 경우 의미가 있습니다 myFunction.js을 블랙 박스로 생각하십시오. 여기에서 가져 오기 또는 함수 인수와 같이 들어오는 것을 제어하고, 나오는 것을 테스트 할 수 있습니다. 그러나 상자 내부에서 일어나는 일을 테스트 할 수는 없습니다.

    여기 목록에있는 2 점을 반영

    import { resetModal } from '../myFunctions.js'; 
    import clearSomethingInModal from 'clearSomethingInModal'; 
    
    jest.mock('clearSomethingInModal',() => jest.fn()) 
    
    describe('resetModal',() => { 
        it('calls the clearSomethingInModal function',() => { 
        resetCreationModal(); 
        expect(clearSomethingInModal.mock.calls.length).toBe(1); 
        }) 
    }) 
    

    myFunctions.js

    import clearSomethingInModal from 'clearSomethingInModal'; 
    
    export resetModal() { 
        clearSomethingInModal() 
    } 
    

    myFunctions.test.js

    myFunctions.test.js 두 일례이다

    import { resetModal } from '../myFunctions.js'; 
    
    describe('resetModal',() => { 
        it('calls the clearSomethingInModal function',() => { 
        const clearSomethingInModal = jest.fn(); 
        resetCreationModal(clearSomethingInModal); 
        expect(clearSomethingInModal.mock.calls.length).toBe(1); 
        }) 
    }) 
    

    myFunctions.js

    export resetModal(clearSomethingInModal) { 
        clearSomethingInModal() 
    } 
    
  • +1

    감사합니다 안드레아스, 그 좋은 설명입니다. 그래서 나는 그 기능의 구조를 바꾸지 않고 내가 원하는 방식으로 테스트 할 수 없다고 생각한다. 그래서, (a) 그것이 기능의 설계에 문제를 암시하고, (b) 현재의 형태로, 당신이 그것에 적용 할 수있는 유효한 테스트가있을 것입니까? 'resetModal'함수는 간결하게하기 위해 생략 한 여러 함수를 호출합니다. –