问题
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:
Read all your test files and execute them. The callbacks passed to
describe
are executed right away. The callbacks passed toit
and to the hooks (before
,beforeEach
, etc.) are recorded for later execution.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