Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

node.js - Sinon not stubbing on module.exports

If create an file with the following contents

const validateEmail = email => {
    sendEmail(email);
};

const sendEmail = email => {
  return true;
};

module.exports = {
  validateEmail,
  sendEmail,
};

And a test that tries to stub out the second function...

it('Should call sendEmail if a valid email is passed', () => {
  let sendEmailSpy = sinon.stub(checkEmail, 'sendEmail');
  checkEmail.validateEmail('[email protected]');
  assert.isTrue(sendEmailSpy.called);
});

It still calls the sendEmail function and the test fails

However, if I write the module.exports like this:

module.exports = {
  validateEmail(email) {
      this.sendEmail(email);
  },
  sendEmail(email) {
    return true;
  },
};

It stubs it correctly...Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer - context

Long answer - in the first scenario, the exported sendEmail function is not the same as the internal one that is used by validateEmail. The exported function becomes a new property of the object being exported and simply references the internal one.

In the second scenario, you explicitly reference the sendEmail function on the exported object (i.e. this.sendEmail(...)) from validateEmail therefore it will use the stubbed version.

Moral of the story - you can't stub something you can't see.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...