badaboum
badaboum

Reputation: 853

Unit testing Angularjs jasmine

I'm trying to unit test a method in Angularjs controllers using jasminejs and Karma runner my method takes an image path in the argument and transforms that image to text (TESSERACT-OCR).

when i try to call a unit test like this it does not work :

TypeError: Attempted to assign to readonly property. at workFn

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");

}));

when i do the following:

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");

}));

i get this error :

Expected undefined to match 'éàîè'.

can i access the $scope.textes.text value from the test ??

My question is how can i access the $scope.textes.text value that contains ocerised text from my test file ? is it possible i don't think because it is inside an anonymous function.. Is this a correct unit test ? can i have more coverage in this unit test ?can anyone help me i'm new in testing with jasmine

Upvotes: 2

Views: 2576

Answers (1)

moribvndvs
moribvndvs

Reputation: 42497

Normally when unit testing an HTTP call, you set up the expectation against $httpBackend, call the function you are testing normally, then call $httpBackend.flush() to fake the expected HTTP response and complete the call synchronously, then test the outcome.

So, taking a stab at your test, it'd probably look more like this....

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')
}));

Upvotes: 1

Related Questions