我正在尝试用酶和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不是一个函数
谁能帮我理解我做错了什么?
我看到你正在做以下事情:
sinon.spy(instance.socketClient(
message,
user,
));
我猜socketClient是一个对象实例,而不是一个函数,但我不能确定没有看到这部分的代码。
如果你认为你打算监视onSendMessage
的方法socketClient
。 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);
});