Mike
Mike

Reputation: 689

Not able to properly stub with proxyquire

I can't wrap my head around proxyquire. I have this auditEvent method, part of auditEvent.js:

const {verify} = require('@mycompany/verifylib');

const auditEvent = () => {
    blabla();
    verify();  // I want to make this call do nothing
    blablabla();
};

module.exports = { auditEvent };

test.js:

const sinon = require('sinon');
const proxyquire = require('proxyquire');

let verifyStub = sinon.stub();

let auditEvent = proxyquire('./auditEvent', {
  '@mycompany/verifylib': {
    verify: verifyStub,
    '@noCallThru': true,
  },
});

auditEvent();   // fails - not a valid function - what am I doing wrong?

Upvotes: 1

Views: 283

Answers (1)

Lin Du
Lin Du

Reputation: 102307

You should deconstruct the auditEvent function from ./auditEvent module.

E.g.

auditEvent.js:

const { verify } = require('@mycompany/verifylib');

const auditEvent = () => {
  verify();
};

module.exports = { auditEvent };

auditEvent.test.js:

const sinon = require('sinon');
const proxyquire = require('proxyquire');

describe('68370747', () => {
  it('should pass', () => {
    let verifyStub = sinon.stub();

    let { auditEvent } = proxyquire('./auditEvent', {
      '@mycompany/verifylib': {
        verify: verifyStub,
        '@noCallThru': true,
      },
    });

    auditEvent();
    sinon.assert.calledOnce(verifyStub);
  });
});

test result:

  68370747
    ✓ should pass (1301ms)


  1 passing (1s)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 auditEvent.js |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------

Upvotes: 2

Related Questions