javascript - 如何在 watch 模式下进行任何 mocha 测试之前运行全局设置脚本

标签 javascript typescript unit-testing vue.js mocha.js

我想以 TDD 方式(--watch 模式)运行 mocha 测试,效果很好。 但是我有一个“global setup.js”文件,它模拟了应用程序的一部分,被大多数测试使用。

如果我第一次正常运行测试或在监视模式下运行测试,一切都很好,因为安装脚本已加载。

但是,如果更改了测试或源文件,则只会运行相关测试(理论上听起来很棒),但由于我的全局模拟脚本未运行,因此测试失败。

即使在使用 mocha 的 watch 模式下,我如何每次(每次整体测试运行一次)执行设置脚本?

这是我使用的命令:

vue-cli-service test:unit --watch
# pure mocha would be (I assume)
mocha 'tests/**/*.spec.js' --watch

我尝试过使用 --require 和 --file 选项,但它们也不会在文件更改时重新运行。

我正在使用通过 VUE CLI 创建的 vue 应用程序,这就是我的代码的样子

// setup.spec.js
import { config } from "@vue/test-utils";

before(() => {
  config.mocks["$t"] = () => {};
});

// some_test.spec.js
import { expect } from "chai";
import { shallowMount } from "@vue/test-utils";

import MyComp from "@/components/MyComp.vue";

describe("MyComp", () => {
  it("renders sth", () => {
    const wrapper = shallowMount(MyComp);

    expect(wrapper.find(".sth").exists()).to.be.true;
  });
});

最佳答案

这不是一个非常令人满意的答案,因为感觉应该有更好的方法,但您可以将设置脚本导入到单独的测试文件中。

例如:

// some_test.spec.js
import 'setup.spec.js' //<-- this guy right here
import { expect } from "chai";
import { shallowMount } from "@vue/test-utils";

import MyComp from "@/components/MyComp.vue";

describe("MyComp", () => {
  it("renders sth", () => {
    const wrapper = shallowMount(MyComp);

    expect(wrapper.find(".sth").exists()).to.be.true;
  });
});

感觉不是最优的,但总比到处复制逻辑要好。

关于javascript - 如何在 watch 模式下进行任何 mocha 测试之前运行全局设置脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56715434/

相关文章:

javascript - 谷歌 API V3 : computeOffset function

typescript - vuejs 计算属性和模板调试有什么好办法吗?

javascript - TS 如何在方法内使用类变量?

javascript - 一次消耗 3 个元素的 AsyncGenerator?

react-native - 使用 react-navigation 中的 useRoute 进行 Jest 单元测试

javascript - 根据浏览器窗口尺寸自动调整图像大小

javascript - 是否有任何公共(public) API 可以使用 javascript 访问当前时间戳?

c# - 单元测试和数据库

javascript - JavaScript 中的 "if debug"?

php - SQLite不支持drop; Laravel单元测试使用什么