【问题标题】:Vue Cli unit test with jest how to run single test带有笑话的Vue Cli单元测试如何运行单个测试
【发布时间】:2019-07-21 08:43:50
【问题描述】:

我有使用 vue cli 3 的 vue 应用程序。 在设置过程中,我选择 jest 作为测试框架。 要运行我的单元测试,我在 package.json 中有一个脚本:

test:unit": "vue-cli-service test:unit",

为了运行它,我在 vs 代码终端中编写:

npm run test:unit

这会运行我所有符合 package.json 文件的 jest config 部分中设置的规范的测试。

我的问题是如何只运行一个测试。我需要运行一个特定的命令吗?或者是否有适用于此设置的 vscode 扩展。

【问题讨论】:

  • 我尝试为 vscode 安装 jest-runner 扩展,但是当我尝试运行测试时,它总是说“测试套件无法运行”
  • 这能回答你的问题吗? How do I run a single test using Jest?

标签: vuejs2 jestjs vue-cli-3


【解决方案1】:

Vue CLI 服务尊重 Jest 的 CLI 选项,因此您可以将它们附加到 package.json 中的命令中,例如

{
  ...
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "test:only": "vue-cli-service test:unit --testPathPattern=user.store",
  },
  "dependencies": { 

testPathPattern 采用适用于规范文件名的正则表达式,因此在我的测试中,如果我指定模式

--testPathPattern=user.store  

我运行单个规范文件,但如果我指定了

--testPathPattern=store

我运行多个名称中带有 store 的匹配规范文件。

这里是Jest docs ref

【讨论】:

  • 这不能回答问题。这会运行该特定规范文件中的所有测试,而不是“单个测试”
  • @coler-j,你可以试试it.only(...)testPathPattern 选项。
【解决方案2】:

如果您只想执行单个文件,那么只需执行以下操作:

npm run test:unit -t counter
OR
npm run test:unit counter

而 counter.spec.js 是我的测试文件。

【讨论】:

  • 这对我不起作用。它只是说0 passing 并且不运行任何测试。
  • 我必须这样做npm run test:unit -t tests/unit/Foo.spec.ts
【解决方案3】:

为此,您可以使用only 方法。它可以直接链接到test 方法。

myunittests.spec.js

describe('My Unit Tests', () => {
    test('My excluded test', () => {
        ...
    })

    test.only('my single test', () => {
        ...
    })
})

之后,您可以通过运行 npm run test:unit -t myunittests 来运行测试。

还有一个skip方法可以被链接。

myunittests.spec.js

describe('My Unit Tests', () => {
    test('My excluded test', () => {
        ...
    })

    test.skip('my single test', () => {
        ...
    })
})

再次运行npm run test:unit -t myunittests,您将看到所有“其他”测试都在运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2020-12-15
    • 2015-10-17
    • 1970-01-01
    • 2021-08-27
    • 2011-02-10
    相关资源
    最近更新 更多