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


当前回答

我们在Angular中使用了nrwl-nx。在这种情况下,我们可以使用这个命令:

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

注:

npm test will run the test script specified in package.json: "test": "ng test" --: tells npm to pass the following parameters to the test script (instead of consuming them) Thus the rest of the cmd will be passed to ng test <ng-project> is the name of a project in angular.json when you omit this parameter, the "defaultProject" (specified in angular.json) will be used (so you must specify it, when the test is not in your default project) Next we must check which builder is used: In angular.json navigate to "project" - "<ng-project>" - "architect" - "test" and check the "builder", which in our case is: "@nrwl/jest:jest" Now that we know the builder, we need to find the available cmd-line parameters On the command line, run npm test <ng-project> -- --help to see all available options Or check the online documentation One of the options is --testFile which is used here

其他回答

不需要传递完整的路径。只需使用正则表达式模式。

看到——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
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'

至少从2019年开始:

NPM test——bar.spec.js

2015年:

为了运行特定的测试,您需要使用jest命令。NPM测试无效。要在命令行上直接访问jest,可以通过npm i -g jest-cli或yarn global add jest-cli安装它。

然后使用jest bar.spec.js运行特定的测试。

注意:您不必输入测试文件的完整路径。参数被解释为正则表达式。完整路径的任何部分都可以唯一地标识一个文件。

你可以使用npm test的文件名——

npm test -- fileName.jsx 

你所要做的就是念咒语

npm test -- SomeTestFileToRun

standalone——是*nix的魔法,用于标记选项的结束,这意味着(对于NPM)之后的所有内容都传递给正在运行的命令,在这种情况下是玩笑。顺便说一句,您可以这样显示Jest的使用说明

npm test -- --help

总之,高喊

npm test -- Foo

运行命名文件(FooBar.js)中的测试。不过,你应该注意:

Jest将名称视为区分大小写的,因此如果您正在使用不区分大小写但保留大小写的文件系统(如Windows NTFS),则可能会遇到奇怪的情况。 Jest似乎将规范视为前缀。

所以上面的咒语会

运行FooBar.js, Foo.js和FooZilla.js 但不是运行foo.js