小编Geh*_*han的帖子

AngularJS测试:模拟$ httpBackend - 处理成功和错误方法

更新:我设法进一步缩小问题范围,并通过更新包含一些无效ascii字符的 httpBackend.when请求来修复意外请求错误.

我已经附加了一个Plunker与他当前的代码块.

但是我仍然难以有效地测试触发成功和错误方法操作.我还需要增加检查消息广播的期望.

为了测试上面提到的场景,我设计了一个我已经包含在Plunker中的hack,但我相信应该有更好的方法来测试这些场景.

任何有关如何克服此问题并测试响应消息状态的线索将非常感激.

问题

我为我的测试设置了$ httpBackend的预期值/响应,但是当我运行$ httpBackend.flush()时,它无法指示下面提到的错误.

指示错误消息

Error: Unexpected request: GET https://192.168.1.10:3334/res?t1=CHECK&t2='?'&req={"_msgType":"Login_msg","UserName":"e@e.com","Password":"123"}
Run Code Online (Sandbox Code Playgroud)

我确实找到了一些讨论这个问题域的有用链接,它们确实帮助我缩小了问题范围.但我似乎还无法弄清楚这个单元测试失败的具体原因.

有用的堆栈溢出问题

有用的外部资源

我也试过移动flush()调用,并尝试调用$ apply或$ digest,如此处所示,在测试中发出$ http请求.

要测试的AngularJS服务

    app.service('restService',['$log','$http','$rootScope',function($log,$http,$rootScope)
{
    this.location = null;
    this.port = null;

    this.sendRequest = function(host,port,param1,param2,requestMsg)
    {
        this.location = host;
        this.port = port;
        $http.get('https://'+host+":"+port+"/res?t1="+param1+"&t2="+param2+"&req="+JSON.stringify(requestMsg)).
        success(function(data) { 
           //Need …
Run Code Online (Sandbox Code Playgroud)

unit-testing angularjs angularjs-service httpbackend karma-jasmine

5
推荐指数
1
解决办法
2064
查看次数