728x90
반응형
모의 구현
jset.fn 은 모의 함수 또는 메서드를 mockImplementationOnce
를 사용하여 수행할 수있다
mockImplementationOnce 메서드는 다른 모듈에서 생성된 모의 함수의 기본 구현을 정의해야 할 때 유용하다
const myMockFn = jest.fn(cb => cb(null, true));
myMockFn((err, val) => console.log(val));
// > true
// foo
export function () {
// some implementation;
};
// test
jest.mock('../foo'); // this happens automatically with automocking
import foo from '../foo'
// foo is a mock function
foo.mockImplementation(() => 42);
foo();
// > 42
여러 함수 호출이 다른 결과를 생성하도록
모의 함수의 복잡한 동작을 테스트 하는 경우 mockImplementationOnce
메서드 사용
const myMockFn = jest
.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
myMockFn((err, val) => console.log(val));
// > true
myMockFn((err, val) => console.log(val));
// > false
모의 함수가 mockImplementationOnce
로 정의된 구현에서 실행되면
jest.fn으로 설정된 기본 구현(정의된 경우)을 실행한다
const myMockFn = jest
.fn(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
// > 'first call', 'second call', 'default', 'default'
일반적으로 연결된(그래서 항상 이것을 반환해야 하는) 메서드가 있는 경우
모든 모의에 있는 .mockReturnThis() 함수의 형태로 이를 단순화하는 달콤한 API가 있다
const myObj = {
myMethod: jest.fn().mockReturnThis(),
};
// is the same as
const otherObj = {
myMethod: jest.fn(function () {
return this;
}),
};
반응형
댓글