【问题标题】:Unit testing Angularjs jasmine单元测试 Angularjs 茉莉花
【发布时间】:2013-12-25 09:26:06
【问题描述】:

我正在尝试使用 jasminejs 和 Karma runner 对 Angularjs 控制器中的方法进行单元测试 我的方法在参数中采用图像路径并将该图像转换为文本 (TESSERACT-OCR)。

当我尝试像这样调用单元测试时它不起作用:

TypeError:试图分配给只读属性。 在工作中Fn

it('has to return text from image', inject(function($httpBackend) {
 $scope.ocr("./image.png");
 $httpBackend.expectPOST('/ocr').respond();
 expect( scope.oceriser.bind("./ocr.png")).toMatch("ocr");

}));

当我执行以下操作时:

it('has to return text from image', inject(function($httpBackend) {
 $scope.ocr("./image.png");
 $httpBackend.expectPOST('/ocr').respond();
 expect($scope.ocr("./ocr.png")).toMatch("ocr");

}));

我得到这个错误:

预期未定义以匹配“éàîè”。

我可以从测试中访问 $scope.textes.text 值吗??

我的问题是如何从我的测试文件中访问包含 ocerised 文本的 $scope.textes.text 值?有没有可能我不认为因为它在一个匿名函数中.. 这是一个正确的单元测试吗?我可以在这个单元测试中有更多的覆盖范围吗?谁能帮我我是新来的茉莉花测试

【问题讨论】:

    标签: unit-testing angularjs jasmine karma-runner


    【解决方案1】:

    通常在对HTTP调用进行单元测试时,对$httpBackend设置期望,正常调用你正在测试的函数,然后调用$httpBackend.flush()来伪造期望的HTTP响应并同步完成调用,然后测试结果.

    所以,试一试你的测试,它可能看起来更像这样......

    it('has to return text from image', inject(function($httpBackend) {
    
     var expected = {}; // the value expected from the HTTP request
    
     // set up the http expectation. this tells angular what you expect to have called through $http when flush() is called
     $httpBackend.expectPOST('/oceriser').respond(expected);
    
     // call the function you are testing
     scope.oceriser('./image.png');
    
     // flushes the pending fake HTTP response causing the call to oceriser above to complete synchronously, and the function will continue normally
     $httpBackend.flush();
    
     // now, verify that oceriser() did what you expect when the http call succeeds. you'll need to figure this out, but in this example, i assume textes contains no elements initially, but after oceriser is called, it will contain one element with the text property equal to expected
     expect(scope.textes.length).toBe(1);
     expect(scope.textes[0].text).toBe(expected);
     expect(scope.textes[0].source).toBe('./image.png')
    }));
    

    【讨论】:

    • 当我将数组$scope.textes.push 更改为$scope.textes = {source : source , text : text } 之类的对象以及尝试访问expect(scope.textes.text).toBe(expected); 之类的单元测试文件中的属性文本时,我遇到了问题,因为scope.textes。 text 属性具有与预期变量相同的值。有任何想法吗 ??我需要在flush()之后使用scope.$digest()来同步范围吗??
    • 不,$digest 不是必需的,因为这将在 http 请求期间为您处理好。这可能是一个平等的问题。 toBe 期望值完全相同,或者在对象的实例中,对象是相同的实例。如果您克隆/复制它 看起来 相同但是不同的实例,则测试将失败。如果您期望完全相同的实例并且它失败了,只需单步执行您的代码,看看哪里出错了。
    • 如果您想测试以确保测试中的所有数据都相同,您可以添加自己的茉莉花匹配器(在测试之前添加您的描述)。 beforeEach(function(){ this.addMatchers({ toEqualData: function(expected) { return angular.equals(this.actual, expected); } }); });
    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2022-01-23
    • 2020-11-25
    • 2020-08-19
    • 2015-10-01
    相关资源
    最近更新 更多