

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 Jest 設定測試報告
<a name="test-report-jest"></a>

下列程序示範如何使用 Jest 測試架構 AWS CodeBuild 在 中設定測試報告。 [https://jestjs.io/](https://jestjs.io/)

此程序需要下列先決條件：
+ 您有現有的 CodeBuild 專案。
+ 您的專案是設定為使用 Jest 測試框架的 Node.js 專案。

將 [https://www.npmjs.com/package/jest-junit](https://www.npmjs.com/package/jest-junit) 套件新增至您專案的 `package.json` 檔案的 `devDependencies` 區段。CodeBuild 使用此套件來產生 `JunitXml` 格式的報告。

```
npm install --save-dev jest-junit
```

如果尚未存在，請將 `test` 指令碼新增至專案的 `package.json` 檔案中。`test` 指令碼可確保在 **npm test** 執行時呼叫 Jest。

```
{
  "scripts": {
    "test": "jest"
  }
}
```

將以下內容新增至您的 Jest 組態檔，以將 Jest 設為使用 `JunitXml` 報告程式。如果您的專案沒有 Jest 組態檔，請在您專案的根目錄中，建立一個名為 `jest.config.js` 的檔案，並新增以下內容。測試報告會匯出至 *<test report directory>*/*<report filename>* 指定的檔案。

```
module.exports = {
  reporters: [
    'default',
    [ 'jest-junit', {
      outputDirectory: <test report directory>,
      outputName: <report filename>,
    } ]
  ]
};
```

在您的 `buildspec.yml` 檔案中，新增/更新以下區段。

```
version: 0.2

phases:
  pre_build:
    commands:
      - npm install
  build:
    commands:
      - npm build
      - npm test

reports:
  jest_reports:
    files:
      - <report filename>
    file-format: JUNITXML
    base-directory: <test report directory>
```