프로젝트를 진행하면서 TDD(테스트 주도 개발) 많이들 사용하실 겁니다.
테스트 코드를 짜는게 꼭 절대적으로 좋다라고는 말할수는 없지만 단위테스트 정도는 무리가지 않으니 많이하고 있는걸로 압니다.
오늘은 Nuxt3로 프로젝트를 하면서 사용한 테스트 프레임워크 Jest를 설정하고 사용해 보는법을 정리해 보고자 합니다.
nuxt프로젝트를 cli로 만들때 단위테스트를 선택하는 부분이 있는데 선택하면 자동으로 설치해줍니다.
저는 프로젝트 생성시에 선택하지 않아서 수동으로 설치해 줬습니다.
Nuxt프로젝트 생성
수동으로 선택해서 프로젝트 생성시
npm init nuxt-app
기본설정으로 프로젝트 생성시
npx nuxi init
Dependency install
수동으로 프로젝트 생성시에 Testing Framework를 선택해줄 수 있습니다


프로젝트 생성시에 Jest를 선택해줬으면 별 설정이 필요없을겁니다.
저 같은 경우에는 수동으로 설치했기 때문에 설정이 필요합니다.
// jest.config.ts
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
moduleFileExtensions: ["js", "vue", "ts", "json", "tsx"],
moduleNameMapper: {
// "^@/(.*)$": "<rootDir>/$1",
"^~/(.*)$": "<rootDir>/$1",
"^@/(.*)$": "<rootDir>/src/$1",
"#imports": "<rootDir>/.nuxt/imports.d",
},
transform: {
"^.+\\.(js)$": "babel-jest",
".+\\.(css|scss|png|jpg|svg)$": "jest-transform-stub",
".*\\.(vue)$": "@vue/vue3-jest",
"^.+\\.(ts|tsx)$": "ts-jest",
},
transformIgnorePatterns: [
"node_modules/(?!(nuxt3|unenv))",
// "node_modules/(?!pinia/.*)",
// "<rootDir>/node_modules/(?!@pinia/testing)",
],
moduleDirectories: ["node_modules", "src"],
// roots: ["<rootDir>/src"],
};
"scripts": {
"test": "jest"
},
// test.spec.ts
import LoginLayer from "~/src/ui/views/admin/LoginAdmin.vue";
import { mount, shallowMount } from "@vue/test-utils";
import { setActivePinia, createPinia } from "pinia";
// import { createTestingPinia } from "@pinia/testing";
describe("단위테스트", () => {
let wrapper = null;
beforeEach(() => {
setActivePinia(createPinia());
wrapper = mount(LoginLayer);
});
it("테스트 단위", () => {
expect("test success");
});
});
PASS tests/unit/specs/test/test.spec.ts (20.435 s)
단위테스트
✓ 테스트 단위 (92 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 21.586 s