我能够使用Jest测试多个文件,但我不知道如何测试单个文件。

我有:

执行npm install jest-cli——save-dev命令 更新包。Json: '{…"scripts": {"test": "jest"}…} 编写了许多测试。

运行npm测试可以正常工作(目前运行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'


当前回答

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'

其他回答

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'

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

yarn test src/lib/myfile.test.js

这是我包裹里的零件。Jest作为本地包安装在json文件中(删除了相关部分):

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

}

你有两个选择:

Option 1: Command line. You can run the following command 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' This avoids you to install Jest globally. You use the jest used by your project. Option 2: If you are using Visual Studio Code you have a great plugin to do this: Jest Runner. It allows you not only to run tests file by file, but even specific suites and specs just by a right click on the tests you want to run.

当时我用的是:

yarn test TestFileName.spec.js

你不应该输入完整路径。对我来说,这在Windows 10电脑上是可行的。

用一个包裹。json脚本

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

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

直接使用jest-cli

Globally-installed:

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