---
# System prepended metadata

title: JEST 安裝
tags: [JEST]

---

---
tags: JEST
---


# JEST 安裝

## VUE-CLI 3 安裝方式
```shell=
vue add unit-jest
```

## VUE-CLI 2 安裝方式

* 安裝 Jest
```shell=
// npm
$ npm install --save-dev babel-jest
$ npm install --save-dev babel-plugin-dynamic-import-node
$ npm install --save-dev babel-plugin-transform-es2015-modules-commonjs
$ npm install --save-dev jest jest-serializer-vue jest-watch-typeahead
$ npm install --save-dev @vue/test-utils vue-jest
```

* 然後我們需要在 package.json 中定義一个單元測試的腳本。
```javascript=
// package.json
{
  "scripts": {
    "unit": "jest --config test/unit/jest.conf.js --coverage",
    "test": "npm run unit"
  }
}
```

* 修改 Babel 配置
```javascript=
// .babelrc
{
  // 沿用原本配置
  "presets": [...],
  // 增加 env 區塊
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
    }
  }
}

```

* 接下来在 根目錄 中創見一個 jest 區塊：
    * /test/unit/.eslintrc
    ```javascript=
    {
      "env": {
        "jest": true
      },
      "globals": {}
    }
    ```

    * /test/unit/jest.conf.js
    ```javascript=
    const path = require('path')

    module.exports = {
      // Indicates whether each individual test should be reported during the run. 
      // All errors will also still be shown on the bottom after execution.
      verbose: true,
      rootDir: path.resolve(__dirname, '../../'),
      moduleFileExtensions: ['js', 'json', 'vue'],
      // 如果你在 webpack 中配置了别名解析，比如把 @ 设置为 /src 的别名，那麼你也需要用 moduleNameMapper 選項為 Jest 增加一个匹配配置：
      moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
      },
      transform: {
        '^.+\\.js$': '<rootDir>/node_modules/babel-jest', // 用 `babel-jest` 處理 js
        '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest', // 用 `vue-jest` 處理 `*.vue` 文件
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/fileTransformer.js',
      },
      // 自定義的序列化工具改進被保存的快照
      snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
      setupFiles: ['<rootDir>/test/unit/setup'],
      // 測試覆蓋率
      coverageDirectory: '<rootDir>/test/unit/coverage',
      collectCoverageFrom: [
        'src/**/*.{js,vue}',
        '!src/main.js',
        '!src/router/index.js',
        '!**/pwa/**',
        '!**/assets/**',
        '!**/node_modules/**',
      ],
      testMatch: ['**/test/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'],
      testEnvironment: 'jsdom',
      testURL: 'http://localhost/',
    }
    ```

    * /test/unit/setup.js
    ```javascript=
    import Vue from 'vue'

    Vue.config.productionTip = false
    ```

    * /test/unit/specs/HelloWorld.spec.js
    ```javascript=
    import { shallowMount } from '@vue/test-utils'

    // The component to test
    const MessageComponent = {
      template: '<p>{{ msg }}</p>',
      props: ['msg'],
    }

    test('displdays message', () => {
      // mount() returns a wrapped Vue component we can interact with
      const wrapper = shallowMount(MessageComponent, {
        propsData: {
          msg: 'Hello world',
        },
      })

      // Assert the rendered text of the component
      expect(wrapper.text()).toContain('Hello world')
    })
    ```
    * support images
    add /fileTransformer.js
    ```javascript=
    const path = require('path')

    module.exports = {
      process(src, filename, config, options) {
        return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'
      },
    }
    ```
    
    
### 修正 VSCODE JEST 套件無法直接 debuger

* 修改 package.json 中的单元测试的腳本
VSCODE 的 JEST 套件 抓取 jest 配置於根目錄
```javascript=
// package.json
{
  "scripts": {
    "unit": "jest --config jest.config.js --coverage",   
    //"unit": "jest --config test/unit/jest.conf.js --coverage",
    "test": "npm run unit"
  }
}
```

* 修改 /test/unit/jest.conf.js -> /jest.config.js
    ```javascript=
    const path = require('path')

    module.exports = {
      // Indicates whether each individual test should be reported during the run. 
      // All errors will also still be shown on the bottom after execution.
      verbose: true,
      //rootDir: path.resolve(__dirname, '../../'), // 不需要指定根目錄
      moduleFileExtensions: ['js', 'json', 'vue'],
      // 如果你在 webpack 中配置了别名解析，比如把 @ 设置为 /src 的别名，那麼你也需要用 moduleNameMapper 選項為 Jest 增加一个匹配配置：
      moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
      },
      transform: {
        '^.+\\.js$': '<rootDir>/node_modules/babel-jest', // 用 `babel-jest` 處理 js
        '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest', // 用 `vue-jest` 處理 `*.vue` 文件
        '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/fileTransformer.js',
      },
      // 自定義的序列化工具改進被保存的快照
      snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
      setupFiles: ['<rootDir>/test/unit/setup'],
      // 測試覆蓋率
      coverageDirectory: '<rootDir>/test/unit/coverage',
      collectCoverageFrom: [
        'src/**/*.{js,vue}',
        '!src/main.js',
        '!src/router/index.js',
        '!**/pwa/**',
        '!**/assets/**',
        '!**/node_modules/**',
      ],
      testMatch: ['**/test/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'],
      testEnvironment: 'jsdom',
      testURL: 'http://localhost/',
    }
    ```

