© 2020-present Sungjin Cho.
All Rights Reserved
typescript 프로젝트에서는 ts-jest
, @testing-library/react
를 사용한다.
ts-jest
는 tsx 파일을 사용하기 위해서 사용한다.@testing-library/react
는 hooks 테스트를 위해서 사용한다./** @type {import('ts-jest').JestConfigWithTsJest} */
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');
module.exports = {
testEnvironment: 'jsdom',
transform: {
'^.+.tsx?$': [
'ts-jest',
{
tsconfig: 'tsconfig.test.json', // nextjs에서는 jsx: preserve로 강제 지정하므로 별도의 tsconfig 파일을 사용한다.
},
],
},
roots: ['.'],
modulePaths: [compilerOptions.baseUrl],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
};
tsconfig.test.json
{
"extends": "tsconfig/nextjs.json",
"baseUrl": ".",
"compilerOptions": {
"baseUrl": "./",
"paths": {},
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"strictNullChecks": false,
"forceConsistentCasingInFileNames": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"noEmit": false,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx", // *.test.tsx 에서는 이 부분 설정이 필요하다.
"sourceMap": true,
"incremental": true,
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
yarn test 시에 아래 에러가 발생했다. 아래 두가지 해결방법이 있었다.
yarn add -D @types/jest
시에 동일한 에러가 또 발생했다. 이때는 yarn.lock 파일을 삭제하고 다시 yarn을 하닌깐 해결되었다.Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/stefancho/works/npm-lib/phantom-depcheck/node_modules/strip-ansi/index.js from /Users/stefancho/works/npm-lib/phantom-depcheck/node_modules/string-width/index.js not supported.
Instead change the require of /Users/stefancho/works/npm-lib/phantom-depcheck/node_modules/strip-ansi/index.js in /Users/stefancho/works/npm-lib/phantom-depcheck/node_modules/string-width/index.js to a dynamic import() which is available in all CommonJS modules.
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at Object.<anonymous> (/Users/stefancho/works/npm-lib/phantom-depcheck/node_modules/string-width/index.js:2:19)
import { describe, expect, jest, test } from '@jest/globals';
import { renderHook, waitFor } from '@testing-library/react';
import { ReactNode } from 'react';
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
import nock from 'nock';
import axios from 'axios';
const queryClient = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
};
const instance = axios.create({
baseURL: 'https://api.mydomain.co.kr/foo/bar',
});
function useFetchData() {
return useQuery('fetchData', async () => {
const res = await instance.get('/api/users/5');
return res;
});
}
describe('hello', () => {
test('test...', async () => {
const e = nock('https://api.mydomain.co.kr/foo/bar')
.defaultReplyHeaders({
'access-control-allow-origin': '*',
'access-control-allow-credentials': 'true',
})
.get('/api/users/5')
.reply(200, {
ans: 'Hello',
});
const { result } = renderHook(() => useFetchData(), { wrapper });
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
const r = result.current.data.data;
expect(r).toEqual({ ans: 'Hello' });
});
});