Reputation: 9184
Let's say I have such code:
...
$scope.articles = [{id: 1}, {id: 2}];
$scope.openArticle = (artId) => {
...
const article = ...;
$http.post(`url`, `body`).then(() => {
article.opened = true;
}, () => {});
};
is there any way to test this with jasmine
?
for example I try so:
...
it('should open article', () => {
expect($scope.articles).toBeDefined();
$scope.toggleFeature(1);
expect($scope.articles[0].opened).toBe(true);
});
...
but sure, it won't work this way - I have a promisse inside
I can't change my code to return anything...
so: is it possible to test such function somehow?
Upvotes: 1
Views: 173
Reputation: 61
Let me show a example with jasmine and $httpBackend.
import moduleTest from '../index';
import dataJsonTest from './dataJsonTest.json';
describe('Controller Test', function() {
let controller;
let httpBackend;
let rootScope;
let scope;
beforeEach(angular.mock.module(moduleTest));
beforeEach(angular.mock.inject(($controller, $httpBackend, $rootScope) => {
controller = $controller;
httpBackend = $httpBackend;
rootScope = $rootScope;
scope = $rootScope.$new();
setHttpExpected();
}));
afterEach(() => {
/* Verifies that all of the requests defined via the expect api were made.
If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.
*/
httpBackend.verifyNoOutstandingExpectation();
/*
Verifies that there are no outstanding requests that need to be flushed.
Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.
*/
httpBackend.verifyNoOutstandingRequest();
});
function setHttpExpected() {
let data = dataJsonTest;
httpBackend.when('GET', '/api/model', data, undefined)
.respond(function(method, url, data, headers){
return [204, data, {}];
});
}
it('Test list return', () => {
let ctrl = controller('myController', {$scope: scope, $rootScope: rootScope});
executeRequestSynchronously(httpBackend);
expect(ctrl.data.length).toBe(3);
});
/**
* https://docs.angularjs.org/api/ngMock/service/$httpBackend
*
* After flush is possible catch the values and expecs with jasmine
*/
var executeRequestSynchronously = (httpBackend) => httpBackend.flush();
});
Upvotes: 1