1

I'm just starting out in Mocha, and I'm struggling to figure this one out.

Let's say I have this Node app (app.js):

var myModule = require('./myModule');
function startingPoint() {
   myModule.myFunction();
}

and I have a module (myModule.js):

exports.myFunction = function() {
   console.log('hello, world');
}

Now, what I'd like to do is test app.js and validate that when I call the function startingPoint, that myModule.myFunction gets called. How would I go about that in Mocha?

Thank you!

Danny Ackerman
  • 997
  • 1
  • 10
  • 25

1 Answers1

0

Lets consider the way with mocha, chai and chai-spy. I have exported startingPoint to have access to it under test.

"use strict"

const chai = require('chai')
const expect = chai.expect
const spies = require('chai-spies')
chai.use(spies);
const startingPoint = require('../app')
const myModule = require('../myModule')

describe('App', () => {

    context('.startingPoint()', () => {

        it('doesn\'t call .myFunction()', () => {
            let spy = chai.spy.on(myModule, 'myFunction')
            expect(spy).not.to.have.been.called()
        });

        it('calls .myFunction()', () => {
            let spy = chai.spy.on(myModule, 'myFunction')
            startingPoint()
            expect(spy).to.have.been.called()
        });

    });

});

output from mocha test

Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47