【问题标题】:inner call unit test with Enzyme and Sinon使用 Enzyme 和 Sinon 进行内部调用单元测试
【发布时间】:2019-08-31 19:19:42
【问题描述】:

我正在尝试用酶和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 不是函数

谁能帮我理解我做错了什么?

【问题讨论】:

  • 尝试先将socketClient初始化为sinon fn。然后调用它的实例(和数据),最后调用 sendMessage 的实例。希望它有效。这是在我的头上,如果您弄清楚了,我可以稍后再进行更详细的查看。我在手机上。
  • Chat.js 和 ChatWindow 是同一个组件吗?你介意分享完整的组件代码吗?
  • @etarhan 他们是同一个组件,我已经编辑了这篇文章
  • 您是否有机会将组件包装在 HOC 中?
  • @DimitrisEfst 我已经尝试过这种方式......但似乎我所做的不正确

标签: javascript unit-testing testing enzyme sinon


【解决方案1】:

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

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

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

如果您认为您打算监视onSendMessagesocketClient 方法。 sinon.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);
});

【讨论】:

  • 嗨,etarhan,感谢您的解决方案,确切地说,我想监视实例方法,但是当我将代码更改为此时,发生了另一个错误....无法读取未定义的属性“onSendMessage” ,我做错了什么
  • 其实我在Chat.js中创建了一个socketEvent类的实例,命名为socketClient,onSendMessage是socketEvent类中定义的函数
  • 在wrapper.instance()里面,有sendMessage函数,并且没有叫socketClient的属性,所以wrapper.instance().socketclient是未定义的,我意识到这个问题,我尝试改变它到它的原始类, const spy = sinon.spy(socketEvent, 'onSendMessage')。理论上,它应该可以成功进行间谍活动,但它抛出了一个错误'TypeError: Attempted to wrap undefined property onSendMessage as function'
  • @HungryBird onSendMessage 不是类方法,而是实例方法。假设 socketEvent 是你的类名,你首先需要用 new socketEvent() 实例化它
  • 是的,你是对的,在我实例化它之后现在spy成功了:) 回到我的聊天组件,当我使用聊天组件实例调用sendMessage时,它仍然抛出TypeError:无法读取属性'onSendMessage'未定义的:(
猜你喜欢
  • 2021-02-22
  • 2023-04-01
  • 2021-03-15
  • 1970-01-01
  • 2016-07-01
  • 2019-10-26
  • 2021-09-27
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多