javascript - 使用 Enzyme 和 Sinon 进行内部调用单元测试

标签 javascript unit-testing testing enzyme sinon

我正在尝试使用 enzyme 和 Sinon 中的内部调用为函数编写测试,但我遇到了一些有关内部调用的问题。

这是我的代码:

Chat.js

sendMssage = text => {
    const { user } = this.props;
    let message = this.messageModel.normalize(text);

    this.socketClient.onSendMessage(message, user);
    this.addMessage(message);
  };

test.js

  it('should call sendMessage function', () => {
    const wrapper = shallow(<Chat />);
    const instance = wrapper.instance();
    sinon.spy(instance.socketClient(
    message,
    user,
  ));
    socketClicent.onSendMessage(message, user);
    Instance.sendMessage(message);
  });

它抛出一个错误:

instance.socketClient is not a function

任何人都可以帮助我了解我做错了什么吗?

最佳答案

我看到您正在执行以下操作:

sinon.spy(instance.socketClient(
  message,
  user,
));

我猜 socketClient 是一个对象实例而不是一个函数,但如果没有看到这部分的代码,我无法确定。

如果您认为您打算监视 socketClient 的方法 onSendMessagesinon.spy 期望您传递函数或对象 + 函数(如果您试图监视实例方法)。尝试以下操作:

sinon.spy(instance.socketClient, 'onSendMessage');

完整的解决方案:

it('should call sendMessage function', () => {
  const wrapper = shallow(<Chat user={user} />);
  const instance = wrapper.instance();
  const socketClient = new socketEvent();
  const spy = sinon.spy(socketClient, 'onSendMessage');
  instance.socketClient = socketClient;
  instance.sendMessage(message);
  sinon.assert.calledWith(spy, message, user);
});

关于javascript - 使用 Enzyme 和 Sinon 进行内部调用单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610740/

相关文章:

javascript - moment 在 Internet Explorer 和 Safari 上返回无效日期

python - 如何在网络服务器中运行 Selenium 脚本?

javascript - 在 Meteor 中调用 collection.fineOne 时出现未定义

unit-testing - 如何对依赖于 ActivatedRoute 参数的组件进行单元测试?

objective-c - 使用 swift 2 对 Objective-C 项目进行单元测试

php - 在 Laravel 4 单元测试中,如何在请求中设置 cookie?

performance - 如何降低我的互联网连接速度,以便我可以测试我的网站在较慢的连接上的外观?

testing - Julia:如何准备和清理 @testset

javascript - Jquery Datatable 没有正确地重新排序我的 json

javascript - 如何检查数组的某一项是否具有真值