简体   繁体   中英

How can I run a global setup script before any mocha test in watch mode

I want to run mocha tests in a TDD manner (--watch mode), which works fine. But I have a "global setup.js" file, which mocks part of the application, that is used by most tests.

If I run the tests normally or in watch mode for the first time everything is fine because the setup script loads.

If a test or source file is changed, however, only the relevant tests run (sounds awesome in theory) but since my global mocking script is not run the tests fail.

How can I execute a setup script each time (once per overall test run) even in watch mode with mocha?

This is the command I use:

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

I have tried using the --require and --file option, but they are also not rerun on file changes.

I am using a vue app created with the VUE CLI and this is how my code looks

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

This isn't a very satisfying answer because it feels like there should be a better way but you can import your setup script into the individual test files.

For example:

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

Feels sub optimal, but it is better than replicating logic everywhere.

Have you tried utilizing .mocharc.js file to setup your mocha configurations before you run a test?


    'use strict';

    module.exports = {
        package: './package.json',
        watch: true,
        timeout: 100000
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM