How to mock socket.io with Angular and Jasmine

心已入冬 提交于 2019-12-06 07:45:42

I ended up using the sockMock object defined in this solution.

I would use Sinon.js to create a mock socket object.

For example, in your beforeEach, initialize socket to be an empty object:

socket = {};

createController() must pass the mock to the controller:

$controller('UserMatchingController', {'$scope': $rootScope, 'socket': socket});

Then in your test do something like this:

socket.emit = sinon.spy(); //Create a spy so we can check if it was called
createController();

expect(socket.emit).toHaveBeenCalledWith('match');

You will need the packages sinon and jasmine-sinon. Also if you are using Karma, it will need karma-sinon. You can find more guidelines on the setup on the respective pages.

EDIT: In your case your mock needs to have on and emit functions every time, as they are needed by the controller. In this case it might be better to put this into the beforeEach function:

socket = {
  emit : sinon.spy(),
  on : sinon.spy()
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!