诗农不存根于 module.exports [英] Sinon not stubbing on module.exports

查看:45
本文介绍了诗农不存根于 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('acorrectemail@therightformat.com');
  assert.isTrue(sendEmailSpy.called);
});

仍然调用了sendEmail函数,测试失败

It still calls the sendEmail function and the test fails

但是,如果我像这样编写 module.exports:

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?

推荐答案

简短回答 - 上下文

长答案 - 在第一种情况下,导出的 sendEmail 函数validateEmail 使用的内部函数不同.导出的函数成为被导出对象的一个​​新属性,并简单地引用内部的.

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.

在第二种情况下,您在 validateEmail 的导出对象(即 this.sendEmail(...))上显式引用了 sendEmail 函数code> 因此它将使用存根版本.

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.

这篇关于诗农不存根于 module.exports的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆