4

I have the following code. Sinon failed to mock doSomething() and printing actual string instead of 'hello'

//file.js

import { doSomething } from 'my-npm-package';
module.exports = () => doSomething();

This is the test file:

//file.spec.js

import sinon from 'sinon';
import { expect } from 'chai';
import * as apis from 'my-npm-package';
import someFunction from '../file';

describe('TEST', () => {
  let stub;
  beforeEach(() => {
    stub = sinon.stub(apis, 'doSomething').returns('hello');
  });

  afterEach(() => {
    stub.restore();
  });

  it('test', async () => {
    someFunction();
    expect(stub.calledOnce).to.equal(true);
  });
});
aiiwa
  • 591
  • 7
  • 27
  • This works as expected for me. It might be an issue with compilation, are you using `webpack` or doing anything unusual with `babel`? – Brian Adams Mar 01 '19 at 04:04
  • when i use `sinon.assert.calledOnce(apis.doSomething);` i get ` AssertError: function doSomething(_x5, _x6) { return _ref2.apply(this, arguments); } is not stubbed ` – aiiwa Mar 01 '19 at 04:11
  • using `--require babel-polyfill` – aiiwa Mar 01 '19 at 04:18

1 Answers1

0

If you look at your module.exports, you'll notice that there isn't a named function. If you set your module like below, you'll notice that apis will have a property on it called doSomething, which you'll be able to stub.

module.exports = { doSomething }

Busch
  • 857
  • 10
  • 29
  • tried it. didn't make any difference. still the stub is ignored it seems – aiiwa Mar 01 '19 at 00:13
  • well, when i manually run apis() or console.log it, i can see that it's available and working file. so dont think its an issue with not having named exports – aiiwa Mar 01 '19 at 02:41