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

inner call unit test with Enzyme and 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);
});