Open7

create-next-appの後にする個人的設定

nu0manu0ma

現時点でcreate-next-appの後にすることをスクラップでまとめる。

フォルダをいろいろ追加

プロジェクト直下に/srcフォルダを作成し、基本的にsrcフォルダ以下を編集するようにする。
/src以下にtypesをフォルダを追加。型はここに配置する。
libとかはここでは省略。

.
├── README.md
├── next-env.d.ts
├── next.config.js
├── node_modules
├── package.json
├── public
├── src // この中にcomponentsやstyle、types、lib、pagesが入る
├── tsconfig.json
└── yarn.lock
nu0manu0ma

eslint + prettierの追加

import文の自動ソートと不要なimportを削除したので下記プラグインを入れる。
testing-libraryのlintも追加。

yarn add --save-dev eslint prettier eslint-config-prettier eslint-plugin-unused-imports eslint-plugin-simple-import-sort eslint-plugin-testing-library

nu0manu0ma

VSCode設定 + eslintとprettierの設定

下記ファイルを追加する。

  • .vscode/settings.json
 {
   "editor.defaultFormatter": "esbenp.prettier-vscode", 
   "editor.formatOnSave": true, 
   "editor.codeActionsOnSave": {
     "source.fixAll.eslint": true
   }
 }

  • .vscode/extensions.json

 {
   "recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"]
 }
  • .prettierrc
 {
   "semi": true,
   "singleQuote": true,
   "tabWidth": 2,
   "useTabs": false
 }
  • eslintrc.json
{
  "extends": ["next", "next/core-web-vitals", "prettier"],
  "parser": "@typescript-eslint/parser",
  "plugins": ["unused-imports", "simple-import-sort"],
  "rules": {
    "unused-imports/no-unused-imports-ts": "error",
    "simple-import-sort/imports": "error"
  }
}

追記: https://github.com/tsconfig/bases#readme これでいいかも

baseUrlの設定

下記をtsconfig.jsonのcompilerOptionsに追加

"baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "~/*": ["test/*"]
    },

package.jsonにformat 追加

  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint:eslint": "eslint . --ext .ts,.tsx,.js,.jsx",
    "lint:prettier": "prettier --check .",
    "lint": "npm run lint:eslint && npm run lint:prettier",
    "fix:eslint": "npm run lint:eslint -- --fix",
    "fix:prettier": "npm run lint:prettier -- --write",
    "fix": "npm run fix:eslint && npm run fix:prettier"
  },
  • lintはCIで使う
  • fixはローカルで使う

linterとformatterのignoreを追加

.eslintignoreと.prettierrignote

node_modules/
build/
dist/
public/
.cache/
.next/
.git/
nu0manu0ma

テスト

基本的には Testing | Next.js に書いてある通りにすればOK。

yarn add --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

  • jest.config.jsを作成
const nextJest = require('next/jest');
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
});
// Add any custom config to be passed to Jest
const customJestConfig = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^~/(.*)$': '<rootDir>/test/$1',
  },
  // setupFilesAfterEnv: ['./jest.setup.js'], MSW用
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);

test以下は~/でアクセスできるようにしておく

nu0manu0ma

MSW

テストする場合は大体mswを入れるが、基本公式サイト通りに設定すればOK。

handlersの中身はAPI毎にまとめて定義しないと、handlers.jsがとんでもない大きさになるので分けること。
スキーマなどある場合、レスポンスは自動生成されるものを使用すると良い。

https://mswjs.io/

ドキュメント通りだが、一応書くと下記。

  • yarn add msw --dev
  • プロジェクト直下にtestフォルダを作成(コンポーネントの近くにtestを書くか、testをまとめて書くかはお任せ、今回はtestフォルダ以下に全てのテストを集める構成にする)
  • mkdir test/mocks
  • touch test/mocks/handlers.ts
    • handler.tsの中身(公式ドキュメントより)
import { rest } from 'msw';
export const handlers = [
  rest.post('/login', (req, res, ctx) => {
    return res(
      ctx.status(200)
    );
  }),
  rest.get('/user', (req, res, ctx) => {
    return res(
      ctx.status(200),
      ctx.json({
        username: 'admin',
      })
    );
  }),
];
  • touch test/mocks/server.js
    server.jsの中身(公式ドキュメントより)
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
// This configures a request mocking server with the given request handlers.
export const server = setupServer(...handlers)
  • jest.setup.jsを作成
import { server } from './test/mocks/server';
// Establish API mocking before all tests.
beforeAll(() => server.listen());
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers());
// Clean up after the tests are finished.
afterAll(() => server.close());
  • jest.config.jsに下記を追加
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js'],
}

あとはコンポーネントのテストを書けばOK。

nu0manu0ma

GitHub Actionsの追加

個人的にPRを作成したらbuildとtestは走らせたいのでGitHub Actionsを設定する。

  • .githubフォルダを作成し、auto_pull_request.yamlを作成し下記を書く。
name: front-test
on:
  pull_request:
    types: [opened, synchronize]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16.x
        uses: actions/setup-node@v3
        with:
          node-version: 16.x
      - run: yarn install
      - run: yarn lint
      - run: yarn test
      - run: yarn build