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


当前回答

一个简单可行的解决方案:

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]

其他回答

使用package.json:

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

下面的方法对我很有效:

npm test -f comm -- -t=first

它会找到文件名中包含“comm”的所有文件,只运行找到的文件中包含“first”的测试。

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",
    ...
  },

}

在特定文件中运行特定测试:

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

npm测试,或笑话可以取代纱线测试,这取决于你喜欢的JS捆绑器。

这将只尝试在包含some-partial-filename的文件中查找测试,并且在这些文件中,测试将需要有一个describe或it指令,例如提到“作为分割节点”

// 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");
  })
})

在Angular和Jest中,你可以把它添加到文件包中。“scripts”下的Json:

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

然后,要为特定文件运行单元测试,可以在终端中写入此命令

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