mfncooper / mockery

Simplifying the use of mocks with Node.js
Other
1.1k stars 60 forks source link

Not mocking anything (Mocha/Chai/ES6) #41

Closed anthony-moyart closed 8 years ago

anthony-moyart commented 8 years ago

Hi,

I'm quite new to JS unit testing (I'm more of a PHP backend developper). I recently worked on an Express API, fully written in ES6 (using babel), and wanted to fortify it with some unit tests.

I managed to setup Mocha & Chai to work like a charm on my "standard" tests, but when it comes to mocks, I can't seem to figure it out. I've tried quite everything I had in mind, but still can't get it to work.

I first needed to mock a class within the elastic search module, and I couldn't get it to work. So I tried it in some lightweight/sandbox files.

I have lib.js (the module I want to mock)

export default {
    val: () => true
};

Then script.js (the module I want to test)

import lib from './lib';

export default {
    exec: () => {
        const val = lib.val();
        if (val) {
            console.warn('Not mocked');
        } else {
            console.log('Mocked !');
        }

        return val;
    }
}

And the full test file (script.spec.js, in the exact same folder as the two others)

import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';

let should = chai.should();
chai.use(sinonChai);

import mockery from 'mockery';
let libMock = {
    val: sinon.stub()
};

libMock.val.returns(false);

mockery.registerSubstitute('./lib', libMock);
mockery.enable({
    warnOnUnregistered: false
});

import script from './script'

describe('script', () => {
    describe('can mock a lib that', () => {
        it('should return false instead of true', () => {
            script.exec().should.equal(false);
            libMock.val.should.have.been.calledOnce();
        });
    })
});

And its output (run in IntelliJ Idea) :

Not mocked

AssertionError: expected true to equal false
Expected :false
Actual   :true
 <Click to see difference>

    at Context.<anonymous> (script.spec.js:25:34)

Process finished with exit code 1

Dependencies :

test/mocha.opts :

--require babel-core/register
--require mocha
--require chai-as-promised
anthony-moyart commented 8 years ago

I finally figured it out. The final test code looks like

let valStub = sinon.stub(lib, 'val').returns(false);

import script from './script'

describe('script', () => {
    describe('can mock a lib that', () => {
        it('should return false instead of true', () => {
            script.exec().should.equal(false);
        });
    })
});

And the test passes

codejet commented 8 years ago

@k4zuk0 how did you make lib available so you can stub something on it? it's not clear to me from your examples.