0

I have my module file with below code

whenever promise is rejected process.exit is called with code 1

module.exports = myPromiseReturningFunc(args)
.then(el => {
  return true;
})
.catch(err => {
  console.error('Error ', err)
  return process.exit(1);
})

// here is my index.test.js
const sinon = require('sinon');
describe('Index', () => {
  let exitStub;
  beforeEach(done => {  
    exitStub = sinon.stub(process, 'exit').callsFake(() => {
      return 'error'
    })
  })
  afterEach(done => {
    process.exit.restore();
  })

  it('should exit with error', (done) => {
    myModuleFunction(args).then(result => {
      expect(result).to.be.eql('error'); // passed here
      done();
    })
  })
})

// another test file
describe('Help Module', () => {
  it('should return true', (done) => {
    myModuleFunction({}).then(result => {
      console.log(result); // prints error here again :-(
      expect(result).to.be.true;
    })
  })
})

I would like to stub the process.exit once and then but it returns the same error in other files also although other function is returning success response

kailash yogeshwar
  • 836
  • 1
  • 9
  • 26
  • The question lacks https://stackoverflow.com/help/mcve . There are no myPromiseReturningFunc and myModuleFunction, while there may cause a problem. Your real code seems to differ from the one you've posted. `expect(result).to.be.eql('error')` - very unlikely, you're not returning `process.exit` (also, doesn't make sense to mock its return value with `error`, asserting that it was called would be enough). `expect(result).to.be.true` - why there be an erro then? You're misusing `done` everywhere. You should either call it or not use it. If a block is sync, it doesn't need `done` – Estus Flask Jul 16 '18 at 11:39
  • @estus if I don't mock process.exit all my further test cases will be halted as the process will be exited and whenever the function returns proper value it would be true so that's the way to assert it. Perhaps the question is why the mock response is shown in another file – kailash yogeshwar Jul 16 '18 at 11:50
  • The point that is you need to stub it, there's no need to mock it with some value - and you can't assert this value in the code above. I can't say why it's shown in another file because there are inconsistencies in the code you've posted. That you incorrectly used `done` certainly affects that but I would expect it to result in test timeouts rather than in behaviour you described. Please, address all the issues I mentioned above. Also, it's better to use https://www.npmjs.com/package/mocha-sinon rather than do restore() manually, particularly because you can avoid human mistakes this way. – Estus Flask Jul 16 '18 at 11:58
  • okay got it will try mocha-sinon – kailash yogeshwar Jul 16 '18 at 13:00

0 Answers0