How to programmatically skip a test in mocha?

前端 未结 14 1173
失恋的感觉
失恋的感觉 2020-12-07 17:31

I have a code where certain tests will always fail in CI environment. I would like to disable them based on an environment condition.

How to programmatically skip a

14条回答
  •  广开言路
    2020-12-07 17:47

    Say I wanted to skip my parametrized test if my test description contained the string "foo", I would do this:

    // Skip parametrized test if description contains the string "foo"
    (test.description.indexOf("foo") === -1 ? it : it.skip)("should test something", function (done) {
        // Code here
    });
    
    // Parametrized tests
    describe("testFoo", function () {
            test({
                description: "foo" // This will skip
            });
            test({
                description: "bar" // This will be tested
            });
    });
    

    In your case, I believe that if you wanted to check environment variables, you could use NodeJS's:

    process.env.ENV_VARIABLE
    

    For example (Warning: I haven't tested this bit of code!), maybe something like this:

    (process.env.NODE_ENV.indexOf("prod") === -1 ? it : it.skip)("should...", function(done) {
        // Code here
    });
    

    Where you can set ENV_VARIABLE to be whatever you are keying off of, and using that value, skip or run the test. (FYI the documentation for the NodeJS' process.env is here: https://nodejs.org/api/process.html#process_process_env)

    I won't take complete credit for the first part of this solution, I found and tested the answer and it worked perfectly to skip tests based on a simple condition through this resource: https://github.com/mochajs/mocha/issues/591

    Hope this helps! :)

提交回复
热议问题