0

I'm very new to angular, or maybe just stupid. But how do I test a controller that uses angular-websocket? It certainly isn't this:

describe('controllers', function(){
    beforeEach(module('myapp.controllers'));

    it('should ....', inject(function($controller) {
        //spec body
        var mycontroller = $controller('mycontroller', { 
                                          $scope: {} ,
                                          WebSocket: WebSocket
    });
    expect(mycontroller).toBeDefined();
}));

2 Answers 2

1

If what you're after is a unit test, then I would create a mock WebSocket (a bit like you use a mock $httpBackend to test $http communication). This mock object would have the same methods as the real WebSocket object but would allow checking that you have sent something to it, and would allow manually triggering the sending of a message or the opening of a connection:

var mockWebSocket = new MockWebSocket();
var mycontroller = $controller('mycontroller', { 
                                      $scope: {} ,
                                      WebSocket: mockWebSocket
});
mockWebSocket.openConnection(); // that internally calls all the registered onopen callbacks
expect(mockWebSocket.send).toHaveBeenCalledWith('hello');
mockWebSocket.sendMessage('goodbye'); // that internally calls all the registered onmessage callbacks
expect($scope.lastReceivedMessage).toBe('goodbye');

Too bad the module doesn't come with such a mock.

Sign up to request clarification or add additional context in comments.

Comments

0

if you were using ngSocket, then you could do the following:

it('should ....', inject(function($controller, ngSocket) {
        //spec body
        var myController = $controller('mycontroller', { 
                                          $scope: {} ,
                                          ngSocket: ngSocket
                                      });
          
        expect(mycontroller).toBeDefined();  
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.