gpt4 book ai didi

angularjs - 模拟Angularjs套接字并在 Jasmine 中测试

转载 作者:行者123 更新时间:2023-12-03 11:58:05 24 4
gpt4 key购买 nike

我有一个在service中工作的angularjs websocket。我想使用onOpen onClose onMessage and send测试socket的基本jasmine事件。这是在service中定义套接字的方式:

angular.module('srvSocket', [])
.service('Socket', function($websocket, localConfig) {

var ws = $websocket('ws://'+localConfig.apiUrl);

ws.onMessage(onMessage);
ws.onError(onError);
ws.onClose(onClose);

ws.onOpen(function () {
console.log('conn opened');
});

function onMessage(data){
console.log('data received');
ws.send(JSON.stringify({test: 'hi'}));
}

function onError(err) {
console.log(err);
};

function onClose() {
console.log('conn closed');
};
});

这是我在测试中使用(尝试)服务的方式:
describe('Service: Socket', function () {

var socket, $websocket, $websocketBackend, lc;

beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock'));
beforeEach(inject(function(_Socket_, _$websocketBackend_, _$websocket_, localConfig){
socket = _Socket_;
lc = localConfig;
$websocket = _$websocket_;
$mockSocketBackend = _$websocketBackend_;
$mockSocketBackend.mock();
}));

it('should connect to socket api', function(){
var url = 'ws://'+config.apiUrl;
$mockSocketBackend.expectConnect(url);
ws = $websocket(url);
expect($mockSocketBackend.isConnected(url)).to.be.above(0);
});
});

这就是我跟随 documentation here的距离。我基本上在寻找的是如何为该服务设置模拟websocket服务器?那将使我能够检验我的所有期望?

最佳答案

我将模拟整个$websocket,如此plunk所示,这样您就可以完全控制要测试的内容。

关于angularjs - 模拟Angularjs套接字并在 Jasmine 中测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37195854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com