How to successfully ignore specs with mocha?

﹥>﹥吖頭↗ 提交于 2020-01-07 01:18:00

问题


I use mocha, and I use "skip" and "only" to run specific specs and tests.

But it seems that each time mocha applies these only on the tests.

so if I have this code:

var expect = require('expect.js');
var logger = require('log4js').getLogger('TestDemo');

describe('test', function(){
    logger.info('this will appear');
    it('should not appear', function(){
        expect(1+1).to.be(5);
    });
});


describe.only('should run', function(){
    logger.info('this will appear to');
    it('should appear', function(){
        expect(5).to.be(5);
    })
});

The output is :

[2014-12-12 13:38:37.276] [INFO] TestDemo - this will appear
[2014-12-12 13:38:37.278] [INFO] TestDemo - this will appear to

However - the first one is unexpected as I use describe.only I don't expect to see prints from any other spec.

Reading their documentation, it should work as I expect it, but it doesn't.

 by appending .skip() you may tell Mocha to simply ignore these suite(s) and test-case(s)

However it seems mocha does not ignore the suite, only the test-case.

How can I achieve this?


回答1:


What you get has to do with how Mocha discovers your test. Basically Mocha does this:

  1. Read all your test files and execute them. The callbacks passed to describe are executed right away. The callbacks passed to it and to the hooks (before, beforeEach, etc.) are recorded for later execution.

  2. Mocha executes what it has recorded for later execution (according to some sensible order which is not important here).

What happens when you specify .only on your second describe is that Mocha does not know that you want to execute only this describe block until it executes it. So when it runs into the first describe it has no reason yet to skip it. So it executes the callback passed to it.

At the end of the day, though Mocha is executing exactly the tests you told it to execute. (When I run your code here, the Mocha run ends with 1 passing meaning exactly one test was executed and it passed.) The test in the first describe is ignored and the test in the second one is executed. If you want to make it so that your calls to logger.info will be executed only if one or more test in your describe block is going to be executed, then put them in before hooks:

var expect = require('expect.js');
var logger = require('log4js').getLogger('TestDemo');

describe('test', function(){
    before(function () {
        logger.info('this will appear');
    });
    it('should not appear', function(){
        expect(1+1).to.be(5);
    });
});


describe.only('should run', function(){
    before(function () {
        logger.info('this will appear too');
    });
    it('should appear', function(){
        expect(5).to.be(5);
    })
});


来源:https://stackoverflow.com/questions/27442944/how-to-successfully-ignore-specs-with-mocha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!