3

I am trying to stub authentication middleware in my unit tests, as is done here. My issue is that the module that I am trying to stub is an ES6 module. As a note, I am not using Babel but instead the "type": "module" in my package.json.

The function that I am trying to stub is called checkAuthentication, and it is inside the authentication module. I am using Mocha for unit testing.

Using Sinon I created the following solution.

import chai from 'chai';
import sinon from 'sinon';
import chaiHttp from 'chai-http';
import authentication from '../middleware/authentication.js';

chai.use(chaiHttp);
const expect = chai.expect;

sinon.stub(authentication, 'checkAuthentication').callsFake(function(req, res, next) {
  return next();
});

import server from '../app.js'

it('Expect a status of 200', async () => {
    const res = await chai.request(server)
      .post('/endpoint')
      .set('content-type', 'application/json')
      .send({data: "apple"})
  
    expect(res).to.have.status(200);
});

Unfortunately, this does not seem to work, as the server is created and does not use the stub function but rather the regular function, and the test does not bypass the authentication middleware. Furthermore, it seems impossible to put this stub function replacement in a beforeEach, as is recommended, because of the necessity to import the server after the stub function is created.

I have also looked at using proxyquire, however, I receive the error "Must use import to load ES Module".

Is there another solution to this issue? I have no attachment to Mocha and would be completely happy utilizing a different tool.

joshLor
  • 1,034
  • 1
  • 12
  • 27

0 Answers0