我能够使用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'


当前回答

也可以通过以下方法实现:

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电脑上是可行的。

使用该命令:

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

也可以通过以下方法实现:

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 -g文件名或

npm test -g fileName

例子:

yarn 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]
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'