테스트 프레임워크 중 가장 많이 쓰이고, CRA에도 기본적으로 탑재되어 React 개발환경에 최적화된 Jest 프레임워크에 대해 알아보고 환경설정 및 예제 작성도 해보았다. 이를 토대로 회사 테스트 환경 구축도 완료.
npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer
bable.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
};
npm install --save-dev @babel/preset-typescript
bable.config.js
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};
test("returns undefined by default", () => {
const mock = jest.fn();
let result = mock("foo");
expect(result).toBeUndefined();
expect(mock).toHaveBeenCalled();
expect(mock).toHaveBeenCalledTimes(1);
expect(mock).toHaveBeenCalledWith("foo");
});
// math.js
export const add = jest.fn();
export const subtract = jest.fn();
export const multiply = jest.fn();
export const divide = jest.fn();
// mock.test.js
import * as app from "./app";
import * as math from "./math";
jest.mock("./math.js");
test("calls math.add", () => {
app.doAdd(1, 2);
expect(math.add).toHaveBeenCalledWith(1, 2);
});
test("calls math.subtract", () => {
app.doSubtract(1, 2);
expect(math.subtract).toHaveBeenCalledWith(1, 2);
});
import * as app from "./app";
import * as math from "./math";
test("calls math.add", () => {
const addMock = jest.spyOn(math, "add");
// calls the original implementation
expect(app.doAdd(1, 2)).toEqual(3);
// and the spy stores the calls to add
expect(addMock).toHaveBeenCalledWith(1, 2);
});
import * as app from "./app";
import * as math from "./math";
test("calls math.add", () => {
// store the original implementation
const originalAdd = math.add;
// mock add with the original implementation
math.add = jest.fn(originalAdd);
// spy the calls to add
expect(app.doAdd(1, 2)).toEqual(3);
expect(math.add).toHaveBeenCalledWith(1, 2);
// override the implementation
math.add.mockImplementation(() => "mock");
expect(app.doAdd(1, 2)).toEqual("mock");
expect(math.add).toHaveBeenCalledWith(1, 2);
// restore the original implementation
math.add = originalAdd;
expect(app.doAdd(1, 2)).toEqual(3);
});