簡體   English   中英

如何使用 Jest 測試單個文件?

[英]How do I test a single file using Jest?

我可以使用 Jest 測試多個文件,但我不知道如何測試單個文件。

我有:

  • 運行npm install jest-cli --save-dev
  • 更新了package.json : `{ ... "scripts": { "test": "jest" } ... }
  • 寫了一些測試。

運行npm test按預期工作(目前它運行 14 個測試)。

如何測試單個文件,例如 test app/foo/__tests__/bar.spec.js

我曾嘗試運行npm test app/foo/__tests__/bar.spec.js (從項目根目錄),但我收到以下錯誤:

npm 錯誤! 錯誤:ENOENT,打開 '/node_modules/app/foo/ tests /bar.spec.js/package.json'

至少從 2019 年開始:

npm test -- bar.spec.js

2015 年:

為了運行特定的測試,您需要使用jest命令。 npm test將不起作用。 要直接在命令行上訪問jest ,請通過npm i -g jest-cliyarn global add jest-cli安裝它。

然后只需使用jest bar.spec.js運行您的特定測試。

注意:您不必輸入測試文件的完整路徑。 該參數被解釋為正則表達式。 唯一標識文件的完整路徑的任何部分都足夠了。

你所要做的就是念誦魔法咒語:

npm test -- SomeTestFileToRun

獨立的--是 *nix 用於標記選項結束的魔法,這意味着(對於 NPM)之后的所有內容都傳遞給正在運行的命令,在本例中為jest 順便說一句,您可以通過說來顯示 Jest 使用說明

npm test -- --help

無論如何,念經

npm test -- Foo

在命名文件 ( FooBar.js ) 中運行測試。 但是,您應該注意:

  • Jest 將名稱視為區分大小寫,因此如果您使用不區分大小寫但保留大小寫的文件系統(如 Windows NTFS ),您可能會遇到看起來很奇怪的事情。

  • Jest 似乎將規范視為前綴。

所以上面的咒語會

  • 運行FooBar.jsFoo.jsFooZilla.js
  • 運行foo.js

要運行單個測試:

npm test -t ValidationUtil # `ValidationUtil` is my module `ValidationUtil.spec.js`

-t - 在它之后,放置一個包含測試名稱的正則表達式

如果你使用Yarn ,你可以在后面直接添加.spec.js.test.js文件:

yarn test src/lib/myfile.test.js

這是我的package.json文件中的一部分,其中 Jest 作為本地包安裝(刪除了相關部分):

{
...
  "scripts": {
    "test": "jest",
    "testw": "jest --watch",
    "testc": "jest --coverage",
...
  },
  "devDependencies": {
    "jest": "^18.1.0",
    ...
  },

}

使用npm test並不意味着 Jest 是全局安裝的。 它只是意味着“測試”被映射到在你的package.json文件中使用 Jest。

以下工作,在項目的根級別:

npx jest [file or directory]

file or directory可以是您要運行的測試文件或包含多個文件的目錄。

如果您安裝 Visual Studio Code 插件Jest Runner

在此處輸入圖像描述

您將在每個describeit上方都有Debug / Run選項。

在此處輸入圖像描述

您可以在 Visual Studio Code 中打開您的測試文件,然后單擊其中一個選項。

您可以將文件名與npm test --一起使用:

npm test -- fileName.jsx 

我們將nrwl-nxAngular一起使用。 在這種情況下,我們可以使用以下命令:

npm test <ng-project> -- --testFile "file-name-part"

筆記:

  • npm test將運行package.json中指定的測試腳本: "test": "ng test"
  • -- :告訴 npm 將以下參數傳遞給測試腳本(而不是使用它們)
  • 因此 cmd 的其余部分將傳遞給ng test
    • <ng-project>angular.json中的項目名稱
      • 當您省略此參數時,將使用"defaultProject" (在angular.json中指定)(因此,當測試不在您的默認項目中時,您必須指定它)
    • 接下來我們必須檢查使用了哪個構建器:
      • angular.json導航到"project" - "<ng-project>" - "architect" - "test"
      • 並檢查"builder" ,在我們的例子中是: "@nrwl/jest:jest"
    • 現在我們知道了構建器,我們需要找到可用的命令行參數
      • 在命令行上,運行npm test <ng-project> -- --help以查看所有可用選項
      • 或查看在線文檔
    • 選項之一是--testFile ,這里使用

要在特定文件中運行特定測試:

yarn test -f "partial-filename" -t "as split node"

npm test或者jest可以替換yarn test ,這取決於你喜歡的 JS bundler。

這只會嘗試在包含some-partial-filename的文件中查找測試,並且在這些文件中,測試需要有一個describeit指令,提及“作為拆分節點”,例如

// In cool-partial-filename.js
describe("with a less indented sibling", () => {
  it("should create a new check-list-item with the same indent as split node", () => {
    console.log("This would run with the invocation above");
  })
})

如果您正在運行npm >= 5.2.0並且您已使用npm i -d jest在本地安裝 Jest 作為devDependencies ,您可以通過執行npx jest /path/to/your/spec.js在特定文件上運行 Jest。

也可以通過以下方式實現:

jest --findRelatedTests path/to/fileA.js

參考( Jest CLI 選項

如何在 Nx monorepo 中實現這一點? 這是答案(在目錄/path/to/workspace ):

npx nx test api --findRelatedTests=apps/api/src/app/mytest.spec.ts

參考和更多信息:如何在 Nx #6 中測試單個 Jest 測試文件

當時,我通過使用:

yarn test TestFileName.spec.js

你不應該輸入完整的路徑。 這適用於我在 Windows 10 機器上。

如果您不想全局安裝 jest,您可以使用

npx jest foo.test.js

使用 package.json 腳本

使用 package.json 中的"scripts": { "test": "jest" }

npm test -- foo/__tests__/bar.spec.js

直接使用 jest-cli

全球安裝:

jest foo/__tests__/bar.spec.js

本地安裝:

./node_modules/.bin/jest foo/__tests__/bar.spec.js

使用--testPathPattern

--testPathPattern選項具有將路徑作為未命名位置參數傳遞給 jest-cli 的等效效果。 請參閱normalize.ts

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js

測試兩個或更多特定文件

用逗號或空格分隔文件名:

./node_modules/.bin/jest foo/__tests__/bar.spec.js,foo/__tests__/foo.spec.js
./node_modules/.bin/jest foo/__tests__/bar.spec.js foo/__tests__/foo.spec.js

通過--testPathPattern多次:

./node_modules/.bin/jest --testPathPattern foo/__tests__/bar.spec.js --testPathPattern foo/__tests__/foo.spec.js

這就是我在不重新啟動測試的情況下對特定文件動態運行測試的方式。

我的 React 項目被創建為create-react-app

所以它監視測試的變化,當我做出改變時自動運行測試。

所以這就是我在終端測試結果結束時看到的:

Test Suites: 16 passed, 16 total
Tests:       98 passed, 98 total
Snapshots:   0 total
Time:        5.048s
Ran all test suites.

Watch Usage: Press w to show more.

W

Watch Usage
 › Press f to run only failed tests.
 › Press o to only run tests related to changed files.
 › Press q to quit watch mode.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press Enter to trigger a test run.

然后按P

Pattern Mode Usage
 › Press Esc to exit pattern mode.
 › Press Enter to filter by a filenames regex pattern.

 pattern ›

 Start typing to filter by a filename regex pattern.

這是在我想在“登錄”文件夾中運行“index.es6.js”文件之后:

Pattern Mode Usage
 › Press Esc to exit pattern mode.
 › Press Enter to filter by a filenames regex pattern.

 pattern › login/index

 Pattern matches 1 file
 › src/containers/Login/index.es6.test.js

這就是我在特定文件上運行測試的方式。

一個有效的簡單解決方案:

yarn test -g fileName

npm test -g fileName

例子:

yarn test -g cancelTransaction

npm test -g cancelTransaction

有關測試過濾器的更多信息:

Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]

簡單的方法是運行單個單元測試文件,就是在終端的根文件夾里面運行命令。

npm test <fileName.test.js>

// For example
npm test utils.test.js

我還嘗試了 Visual Studio Code 的 Jest Runner Extensions,效果很好。

使用這個命令:

npx jest test --runTestsByPath <path-to-file>

下面的命令對我有用。
npx jest -i file-name

不需要指定文件的完整路徑,文件名就足夠了。

編輯:找到另一種方法。
npm run test:functional -i file-name
npm run test:integration -i file-name

無需傳遞完整路徑。 只需使用正則表達式模式。

請參閱--testLocationInResults

yarn jest --testNamePattern my_test_name
yarn jest -t=auth
yarn jest -t component # This will test all whose test name contains `component`

yarn jest --testPathPattern filename # This will match the file path
yarn jest filename # This will match the file path, the same with above

當您使用 jest 時,Jest 和 Jest Runner 是非常有用的 VSCode 擴展。

Jest一個自動測試運行器

Jest Runner在測試上方添加“運行|調試”代碼鏡頭以運行或調試單個測試。

“運行|調試”代碼鏡頭

我剛剛將 Jest 安裝為全局,運行jest myFileToTest.spec.js ,它工作。

如果您使用紗線,請執行此操作

yarn test nameofthefile

例如:

yarn test file.test.js

你有兩個選擇:

  • 選項 1:命令行。 您可以運行以下命令

    node '/Users/complete-path-to-you-project/your-project/node_modules/.bin/jest' '/Users/complete-path-to-you-project/your-project/path-to-your-file-within-the-project/your-file.spec.ts'

    這可以避免您全局安裝 Jest。 您使用項目使用的笑話。

  • 選項 2:如果您使用的是Visual Studio Code ,那么您有一個很棒的插件可以做到這一點: Jest Runner 它不僅允許您逐個文件地運行測試,甚至可以通過右鍵單擊要運行的測試來運行特定的套件和規范。

使用 Angular 和 Jest,您可以將其添加到“腳本”下的文件package.json中:

"test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand"

然后要對特定文件運行單元測試,您可以在終端中編寫此命令

npm run test:debug modules/myModule/someTest.spec.ts

Jest文檔中:

  "scripts": {
    "test": "jest path/to/my-test.js"
  }

運行這個

 npm run test

只需使用此命令運行並檢查特定文件的覆蓋范圍。

yarn run test Index.js -u --coverage --watchAll=false

Jest將使用您傳遞的內容作為正則表達式模式。 它將匹配。

如果要運行特定的測試文件,那么最好的方法是使用它的精確完整路徑。 (您也可以指定某個相對路徑,例如 (src/XFolder/index.spec.ts))。

在目錄和 Linux 中提供完整路徑的最簡單方法是:

jest $PWD/index.spec.ts

注意變量$PWD的使用。

在此處輸入圖像描述

對於 Windows! (要被更新)

import LoggerService from '../LoggerService ';

describe('Method called****', () => {
  it('00000000', () => {
    const logEvent = jest.spyOn(LoggerService, 'logEvent');
    expect(logEvent).toBeDefined();
  });
});

用法:

npm test -- __tests__/LoggerService.test.ts -t '00000000'

對於NestJS用戶,簡單的替代方法是使用,

npm test -t <name of the spec file to run>

NestJS 預先配置了測試文件的正則表達式,以便在 Jest 的情況下進行搜索。

一個簡單的例子是——

npm test -t app-util.spec.ts

(這是我的 .spec 文件名)

不需要給出完整路徑,因為 Jest 會根據NestJS的默認配置搜索 .spec 文件:

"jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

使用 package.json:

  "scripts": {
    "test": "jest --coverage",
    "start": "node index.js"
  }

以下對我有用:

npm test -f comm -- -t=first

它將查找文件名中包含“comm”的所有文件,並且只運行找到的文件中包含“first”的測試。

“測試”:“開玩笑 api/ds_server/ds_server.test.js”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM