在 Node 中使用 Jasmine

jasmine 模組是命令列介面,以及在 Node.js 中執行 Jasmine 規格的支援程式碼。Jasmine 5.x 支援 Node 版本 18、20 和 22。(不支援奇數版的 Node 版本,但許多奇數版本版本都能正常運作。)

安裝

你可以在專案中使用 npm 本機安裝 Jasmine

npm install --save-dev jasmine

透過上述的本機安裝,你可以使用 npx jasmine ... 命令來呼叫 CLI 工具。

你也可以選擇在全域安裝 jasmine,這樣你就能在不帶有 npx 的情況下呼叫 CLI 工具。不過,這並不建議,因為要讓全域安裝的 jasmine 版本與使用它的每個專案同步是很困難的。

npm install -g jasmine

初始化專案

為 Jasmine 初始化專案,方法是建立一個規格目錄和設定檔 json

npx jasmine init

產生範例

產生範例規格和原始碼檔案

npx jasmine examples

在這個時候,你應該能夠 撰寫你的第一個套件

設定

自訂 spec/support/jasmine.json,以列出 Jasmine 執行器要包含的原始碼檔案和規格檔案。你可以使用目錄 glob 字串。

! 開始的檔案會被排除,舉例來說 !**/*nospec.js

spec_dir 用做所有 spec_fileshelpers 的前置字。helper 會在所有規格之前執行一次。要看 helper 的範例,請參閱 React 教學課程

{
  // Spec directory path relative to the current working dir when jasmine is executed.
  // The value "" represents the current working directory.
  "spec_dir": "spec",

  // Array of filepaths (and globs) relative to spec_dir to include and exclude
  "spec_files": [
    "**/*[sS]pec.?(m)js",
    "!**/*nospec.js"
  ],

  // Array of filepaths (and globs) relative to spec_dir to include before jasmine specs
  "helpers": [
    "helpers/**/*.?(m)js"
  ],
  
  // Configuration of the Jasmine environment
  // "env" is optional, as are all of its properties.
  "env": {
    // Whether to fail a spec that ran no expectations
    "failSpecWithNoExpectations": false,
    
    // Stop execution of a spec after the first expectation failure in it
    "stopSpecOnExpectationFailure": false,

    // Stop execution of the suite after the first spec failure  
    "stopOnSpecFailure": false,

    // Run specs in semi-random order
    "random": false
  }
}

你也可以透過使用 --config 命令列引數或 JASMINE_CONFIG_PATH 環境變數來指定不同的設定檔,如下所示。設定檔可以是 .json 或是 .js.js 設定檔應該是一個模組,其預設匯出的值是設定物件。

jasmine JASMINE_CONFIG_PATH=relative/path/to/your/jasmine.json
jasmine --config=relative/path/to/your/jasmine.json

執行規格

在你設定好 jasmine.json 之後,你可以透過從專案的根目錄執行 jasmine (或如果你已經在本地安裝,則執行 npx jasmine)來執行所有規格。

如果你只想執行一個規格,或只執行名稱符合特定 glob 樣式的檔案,你可以做如下操作

npx jasmine spec/appSpec.js
npx jasmine "**/model/**/critical/**/*Spec.js"

過濾規格

只執行其檔名符合給定 glob 的規格

npx jasmine "spec/**/critical/*Spec.js"

或是單一檔案

npx jasmine spec/currentSpec.js

或是只執行其名稱符合特定正規表示式的規格

npx jasmine --filter "adapter21*"

(其中規格的 名稱 是傳遞給 describe() 的第一個參數)

使用 ES 模組

Jasmine 使用動態匯入載入您的程式碼,它應同時與 ES 模組CommonJS 模組 相容。這表示如果腳本的名稱以 .mjs 結尾,或是包含該檔案的套件的 package.json 包含 "type": "module",則腳本會載入為 ES 模組。

預設設定應能適當運作於幾乎所有 CommonJS 計畫及使用 ES 模組的計畫。但如有必要,您可以透過在 Jasmine 設定檔中加入 "jsLoader": "require",設定 Jasmine 使用 require 載入腳本。如果您有使用 "jsLoader": "require" 才能運作,否則無法運作的程式碼,請 告知我們。即使將 jsLoader 設定為 "require",名稱以 .mjs 結尾的檔案仍會透過動態載入載入。

CLI 選項

JASMINE_CONFIG_PATH=

指定設定檔的相對路徑或絕對路徑。可以用作選項或設為環境變數。

JASMINE_CONFIG_PATH=spec/config/jasmine.json jasmine

npx jasmine --config=spec/config/jasmine.json

--no-color

關閉規格輸出的顏色

npx jasmine --no-color

--filter=

僅執行符合給定字串的規格

npx jasmine --filter="a spec name"

--fail-fast

於首次期望結果失敗或其他錯誤後停止執行測試套件

npx jasmine --fail-fast=true

--random=[true|false]

指示 Jasmine 為此次執行以半隨機順序執行規格或不執行,覆寫 jasmine.json

npx jasmine --random=true

--seed=

若啟動隨機化,則設定隨機化種子

npx jasmine --seed=4321

--reporter=

設定預設記者。值必須是可作為模組的記者建構式預設匯出的有效的 匯入字元串

npm i --save-dev jasmine-ts-console-reporter
npx jasmine --reporter=jasmine-ts-console-reporter

使用程式庫

如果您希望更精細地控制設定,亦可以在您的計畫中將 Jasmine 作為程式庫使用。這讓您可以載入多個設定檔或以不同方式控制您的設定。

const Jasmine = require('jasmine');
const jasmine = new Jasmine();

從檔案或物件載入設定

jasmine.loadConfigFile('spec/support/jasmine.json');

jasmine.loadConfig({
    spec_dir: 'spec',
    spec_files: [
        'appSpec.js',
        'requests/**/*[sS]pec.js',
        'utils/**/*[sS]pec.js'
    ],
    helpers: [
        'helpers/**/*.js'
    ]
});

自訂完成處理常式

預設情況下,當測試套件完成執行時,Jasmine 會讓 Node 程序終止。如果套件的 整體狀態'passed',則退出碼會是 0,在所有其他情況中為非零。如果您想要以不同的方式處理完成的情況,您可以將 Jasmine 實例的 exitOnCompletion 屬性設定為 false,並使用 execute 傳回的承諾。這通常可以用於向 grunt 等任務執行器傳送狀態訊息。

jasmine.exitOnCompletion = false;
const result = await jasmine.execute();

if (result.overallStatus === 'passed') {
    console.log('All specs have passed');
} else {
    console.log('At least one spec has failed');
}

記者

如果未加入其他記者,則會包含 ConsoleReporter。您可以使用 configureDefaultReporter 設定預設記者。範例中顯示預設值。

jasmine.configureDefaultReporter({
    // The `timer` passed to the reporter will determine the mechanism for seeing how long the suite takes to run.
    timer: new jasmine.jasmine.Timer(),
    // The `print` function passed the reporter will be called to print its results.
    print: function() {
        process.stdout.write(arguments);
    },
    // `showColors` determines whether or not the reporter should use ANSI color codes.
    showColors: true
});

您可以在 addReporter 加入自訂記者。如果透過 addReporter 加入記者,則不會加入預設的 ConsoleReporter。可以加入多個記者。

const CustomReporter = require('./myCustomReporter');

jasmine.addReporter(new CustomReporter());

執行測試

呼叫 execute 將會執行規格。

jasmine.execute();

execute 可選擇呼叫,並伴隨要執行的規格檔案路徑清單(相對於目前工作目錄),以及依規格名稱篩選的字串。

jasmine.execute(['fooSpec.js'], 'a spec name');

以下是如何使用此函式庫的一個簡單範例

const Jasmine = require('jasmine');
const jasmine = new Jasmine();

jasmine.loadConfigFile('spec/support/jasmine.json');
jasmine.configureDefaultReporter({
    showColors: false
});
jasmine.execute();