program tip

프로그래밍 방식으로 모카에서 테스트를 건너 뛰는 방법은 무엇입니까?

radiobox 2020. 7. 26. 12:50
반응형

프로그래밍 방식으로 모카에서 테스트를 건너 뛰는 방법은 무엇입니까?


CI 환경에서 특정 테스트가 항상 실패하는 코드가 있습니다. 환경 조건에 따라 비활성화하고 싶습니다.

런타임 실행 중에 프로그래밍 방식으로 모카에서 테스트를 건너 뛰는 방법은 무엇입니까?


describe 또는 it 블록 앞에 x를 배치하거나 .skip뒤에 배치하여 테스트를 건너 뛸 수 있습니다 .

xit('should work', function (done) {});

describe.skip('features', function() {});

테스트를 수행하여 단일 테스트를 실행할 수도 있습니다 .only. 예를 들어

describe('feature 1', function() {});
describe.only('feature 2', function() {});
describe('feature 3', function() {});

이 경우 기능 2 블록 만 실행됩니다.

프로그래밍 방식으로 테스트를 건너 뛸 수있는 방법은 없지만 beforeEach명령문 에서 일종의 검사를 수행하고 플래그가 설정된 경우에만 테스트를 실행할 수 있습니다.

beforeEach(function(){
    if (wrongEnvironment){
        runTest = false
    }
}

describe('feature', function(){
    if(runTest){
         it('should work', function(){
            // Test would not run or show up if runTest was false,
         }
    }
}

프로그래밍 방식으로 테스트를 건너 뛰는 문서화되지 않은 방법이 있습니다.

// test.js

describe('foo', function() {
  before(function() {
    this.skip();
  });

  it('foo', function() {
    // will not run
    console.log('This will not be printed');
  });
});

달리는:

$ mocha test.js


  foo
    - foo


  0 passing (9ms)
  1 pending

이것은 https://github.com/mochajs/mocha/issues/1901 에서 논의됩니다 .


이 답변은 ES6에서 작동합니다 .

대신에:

describe('your describe block', () => {

당신이 원하는 :

(condition ? describe : describe.skip)('your describe block', () => {

조건이 거짓이면 설명 블록의 모든 테스트를 조건부로 건너 뜁니다.

또는 대신 :

it('your it block', () => {

당신이 원하는 :

(condition ? it : it.skip)('your it block', () => {

조건이 거짓 인 경우 조건부로 하나의 테스트를 건너 뜁니다.


설명하는 것과 동일한 시나리오에서 Mocha에서 런타임 건너 뛰기를 사용합니다. 문서 의 사본 붙여 넣기입니다 .

it('should only test in the correct environment', function() {
  if (/* check test environment */) return this.skip();

  // make assertions
});

보시다시피 환경에 따른 테스트를 건너 뜁니다. 내 자신의 상태는 if(process.env.NODE_ENV === 'continuous-integration')입니다.


프로그래밍 방식으로 테스트를 건너 뛰려는 방법에 따라 다릅니다. 테스트 코드를 실행 하기 전에 건너 뛰기 조건을 결정할 수 있으면 조건에 따라 호출 it하거나 it.skip필요에 따라 호출 할 수 있습니다 . 예를 들어 환경 변수 ONE가 임의의 값으로 설정된 경우 일부 테스트를 건너 뜁니다 .

var conditions = {
    "condition one": process.env["ONE"] !== undefined
    // There could be more conditions in this table...
};

describe("conditions that can be determined ahead of time", function () {
    function skip_if(condition, name, callback) {
        var fn = conditions[condition] ? it.skip: it;
        fn(name, callback);
    };

    skip_if("condition one", "test one", function () {
        throw new Error("skipped!");
    });

    // async.
    skip_if("condition one", "test one (async)", function (done) {
        throw new Error("skipped!");
    });

    skip_if("condition two", "test two", function () {
        console.log("test two!");
    });

});

확인하려는 조건을 테스트 할 때만 확인할 수 있으면 조금 더 복잡합니다. 테스트 API의 일부를 엄격하게 말하지 않는 것에 액세스하지 않으려면 다음을 수행하십시오.

describe("conditions that can be determined at test time", function () {
    var conditions = {};
    function skip_if(condition, name, callback) {
        if (callback.length) {
            it(name, function (done) {
                if (conditions[condition])
                    done();
                else
                    callback(done);
            });
        }
        else {
            it(name, function () {
                if (conditions[condition])
                    return;
                callback();
            });
        }
    };

    before(function () {
        conditions["condition one"] = true;
    });

    skip_if("condition one", "test one", function () {
        throw new Error("skipped!");
    });

    // async.
    skip_if("condition one", "test one (async)", function (done) {
        throw new Error("skipped!");
    });

    skip_if("condition two", "test two", function () {
        console.log("test two!");
    });

});

첫 번째 예제는 테스트를 공식적으로 건너 뛴 것으로 표시하는 반면 (일명 "보류 중") 방금 보여준 방법은 실제 테스트를 수행하지 않고 테스트는 공식적으로 건너 뛴 것으로 표시되지 않습니다. 합격으로 표시됩니다. 절대로 건너 뛰기를 원한다면 테스트 API의 일부를 올바르게 말하지 않는 부분에 액세스하는 방법이 부족합니다.

describe("conditions that can be determined at test time", function () {
    var condition_to_test = {}; // A map from condition names to tests.
    function skip_if(condition, name, callback) {
        var test = it(name, callback);
        if (!condition_to_test[condition])
            condition_to_test[condition] = [];
        condition_to_test[condition].push(test);
    };

    before(function () {
        condition_to_test["condition one"].forEach(function (test) {
            test.pending = true; // Skip the test by marking it pending!
        });
    });

    skip_if("condition one", "test one", function () {
        throw new Error("skipped!");
    });

    // async.
    skip_if("condition one", "test one (async)", function (done) {
        throw new Error("skipped!");
    });

    skip_if("condition two", "test two", function () {
        console.log("test two!");
    });

});

테스트를 건너 뛰려면 describe.skip또는it.skip

describe('Array', function() {
  it.skip('#indexOf', function() {
    // ...
  });
});

사용할 수있는 테스트를 포함 describe.only하거나it.only

describe('Array', function() {
  it.only('#indexOf', function() {
    // ...
  });
});

https://mochajs.org/#inclusive-tests 에서 자세한 정보


조건부로 테스트를 실행하기 위해 다음과 같이 깔끔한 랩퍼 함수를 ​​작성할 수 있습니다.

function ifConditionIt(title, test) {
  // Define your condition here
  return condition ? it(title, test) : it.skip(title, test);
}

그런 다음 다음과 같이 테스트에서 필요하고 사용할 수 있습니다.

ifConditionIt('Should be an awesome test', (done) => {
  // Test things
  done();
});

패키지 mocha-assume 을 사용하여 프로그래밍 방식으로 테스트를 건너 뛸 수 있지만 테스트 외부에서만 테스트를 건너 뛸 수 있습니다 . 당신은 이것을 다음과 같이 사용합니다 :

assuming(myAssumption).it("does someting nice", () => {});

Mocha-assume은 myAssumptionis true때만 테스트를 실행합니다 . 그렇지 않으면 it.skip좋은 메시지와 함께 테스트 를 건너 뜁니다 (사용 ).

보다 자세한 예는 다음과 같습니다.

describe("My Unit", () => {
    /* ...Tests that verify someAssuption is always true... */

    describe("when [someAssumption] holds...", () => {
        let someAssumption;

        beforeAll(() => {
            someAssumption = /* ...calculate assumption... */
        });

        assuming(someAssumption).it("Does something cool", () => {
            /* ...test something cool... */
        });
    });
});

이 방법을 사용하면 계단식 오류를 피할 수 있습니다. "Does something cool"someAssumption이 유지되지 않으면 테스트 가 항상 실패 한다고 가정하십시오. 그러나이 가정은 이미 위에서 테스트되었습니다 Tests that verify someAssuption is always true".

따라서 테스트 실패는 새로운 정보를 제공하지 않습니다. 사실, 그것은 거짓 양성이기도합니다. "멋진 것"이 효과가 없기 때문에 테스트가 실패하지 않았지만 테스트의 전제 조건이 충족되지 않았기 때문에 테스트가 실패했습니다. 함께 mocha-assume하면 종종 거짓의 양성을 피할 수 있습니다.


I am not sure if this qualifies as „programmatic skipping“, but in order to selectively skip some specific tests for our CI environment, I use Mocha's tagging feature (https://github.com/mochajs/mocha/wiki/Tagging). In describe() or it() messages, you can add a tag like @no-ci. To exclude those tests, you could define a specific "ci target" in your package.json and use --grep and --invert parameters like:

"scripts": {
  "test": "mocha",
  "test-ci" : "mocha --reporter mocha-junit-reporter --grep @no-ci --invert"
}

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! :)


mocha test/ --grep <pattern>

https://mochajs.org/


This is not really using mocha's features, rather tweaking it to get the behaviour I wanted.

I wanted to skip any subsequent 'it's' in my protractor mocha tests and one 'it' failed. This was because once one step of a journey test failed it was almost certain the rest would fail, and may take a long time and hog the build server if they are using browser waits for elements to appear on a page etc.

When just running standard mocha tests (not protractor) this can be achieved with global beforeEach and afterEach hooks by attaching a 'skipSubsequent' flag to the test's parent (describe) like this:

    beforeEach(function() {
      if(this.currentTest.parent.skipSubsequent) {
            this.skip();
      }
    }); 


    afterEach(function() {
      if (this.currentTest.state === 'failed') {
        this.currentTest.parent.skipSubsequent = 'true'
      }
    })

When attempting this with protractor and mocha it the scope of 'this' has changed and the code above does not work. You end up with an error message like 'error calling done()' and protractor halts.

Instead I ended up with the code below. Not the prettiest, but it ends up replacing the implementation of remaining test functions with a this.skip(). This will probably stop working if/when the internals of mocha change with later versions.

It was figured out through some trial and error by debugging and inspecting mocha's internals...helps make browser test suites complete sooner when the tests fail though.

beforeEach(function() {

    var parentSpec = this.currentTest.parent;

    if (!parentSpec.testcount) {
        parentSpec.testCount = parentSpec.tests.length;
        parentSpec.currentTestIndex = 0;
    } else {
        parentSpec.currentTestIndex = parentSpec.currentTestIndex + 1;
    }

    if (parentSpec.skipSubsequent) {

        parentSpec.skipSubsequent = false;
        var length = parentSpec.tests.length;
        var currentIndex = parentSpec.currentTestIndex;

        for (var i = currentIndex + 1; i < length; i++) {
            parentSpec.tests[i].fn = function() {
                this.skip();
            };
        }
    }
});


afterEach(function() {
    if (this.currentTest.state === 'failed') {
        this.currentTest.parent.skipSubsequent = 'true'
    }
});

As @danielstjules answered here there is a way to skip test. @author of this topic has copied answer from github.com mochajs discussion, but there is no info in what version of mocha it available.

I'm using grunt-mocha-test module for integrating mocha test functionality in my project. Jumping to last (for now) version - 0.12.7 bring me mocha version 2.4.5 with implementation of this.skip().

So, in my package.json

  "devDependencies": {
    "grunt-mocha-test": "^0.12.7",
    ...

And then

npm install

And it make me happy with this hook:

describe('Feature', function() {

    before(function () {

        if (!Config.isFeaturePresent) {

            console.log('Feature not configured for that env, skipping...');
            this.skip();
        }
    });
...

    it('should return correct response on AB', function (done) {

        if (!Config.isABPresent) {

           return this.skip();
        }

        ...

Please don't. A test that doesn't work consistently across environments should be acknowledged as such by your build infrastructure. And it can be very disorienting when the CI builds have a different number of tests run than local.

Also it screws up repeatability. If different tests run on the server and local I can have tests failing in dev and passing in CI or vice versa. There's no forcing function and I have no way to quickly and accurately correct a failed build.

If you must turn off tests between environments, instead of conditionally running tests, tag your tests and use a filter to eliminate tests that don't work in certain build targets. That way everybody knows what's going on and it tempers their expectations. It also lets everybody know that there's inconsistency in the test framework, and someone might have a solution that gets them running properly again. If you just mute the test they might not even know there's a problem.

참고URL : https://stackoverflow.com/questions/32723167/how-to-programmatically-skip-a-test-in-mocha

반응형