I am trying to perform unit testing with Karma. I have done everything according to the documentation. When I write this part of the test that follows it never calls the last two functions.
it('should create the mock object', function (done) {
service.createObj(mockObj)
.then(test)
.catch(failTest)
.finally(done);
});
var test = function() {
expect(2).toEqual(1);
};
var failTest = function(error) {
expect(2).toEqual(1);
};
Try to inject into your beforeEach function rootScope. For example like this:
var rootScope;
beforeEach(inject(function (_$rootScope_) {
rootScope = _$rootScope_.$new();
//other injections
}));
and next invoke $digest() after your service method:
it('should create the mock object', function (done) {
service.createObj(mockObj)
.then(test)
.catch(failTest)
.finally(done);
rootScope.$digest();
});
Install angular-mocks module.
Inject module with module in beforeEach.
Inject your service with inject function in beforeEach.
Use $httpBackend to simulate your server.
Do, not forget, to make it, sync. with $http.flush().
Related
Please see my code example below, I have a protractor test that get's run as a GULP task by angular-protractor.
I want to be able to mock some REST calls for all it blocks, but also have access to the httpBackend for specific it blocks.
I'm having trouble sharing the $httpBackend variable around though:
I can't use this.VARIABLE_NAME because of the scope I am in inside the run function.
Code Example
describe('Train Station Search Component', function() {
beforeEach(function() {
//Mock any REST calls here.
browser.addMockModule('httpBackendMock', function() {
angular.module('httpBackendMock', ['MyApp', 'ngMockE2E'])
.run(function($httpBackend) {
//Mock call relevant to both it blocks.
$httpBackend.whenPOST(/^(.*\/api\/search)/).respond({...});
});
});
);
it('should check one piece of functionality', function() {
//Expect call with data relevant only for this it block.
$httpBackend.expectPOST(...);
});
it('should check another piece of functionality', function() {
//Expect call with data relevant only for this it block.
$httpBackend.expectPOST(...);
});
};
Any help appreciated.
You can use $injector to inject $httpBackEnd service.
var $httpBackend
beforeEach(inject(function($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
});
Go through the link https://docs.angularjs.org/api/ngMock/service/$httpBackend
I made a simple demo of a factory and I am trying to test this using jasmine. I am able to run the test but I am using the spyOn method. I would rather use jasmine.createSpy or jasmine.createSpyObj to do the same test. Could someone help me to refactor my code so that uses these methods instead in my example?
http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p=preview
describe('value check',function(){
var $scope,
ctrl,
fac;
beforeEach(function(){
module('app');
});
beforeEach(inject(function($rootScope,$controller,appfactory) {
$scope = $rootScope.$new();
ctrl = $controller('cntrl', {$scope: $scope});
fac=appfactory;
spyOn(fac, 'setValue');
fac.setValue('test abc');
}));
it('test true value',function(){
expect(true).toBeTruthy()
})
it('check message value',function(){
expect($scope.message).toEqual(fac.getValue())
})
it("tracks that the spy was called", function() {
expect(fac.setValue).toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function() {
expect(fac.setValue).toHaveBeenCalledWith('test abc');
});
})
update
angular.module('app',[]).factory('appfactory',function(){
var data;
var obj={};
obj.getValue=getValue;
obj.setValue=setValue;
return obj;
function getValue(){
return data;
}
function setValue(datavalue){
data=datavalue;
}
}).controller('cntrl',function($scope,appfactory){
appfactory.setValue('test abc');
$scope.message=appfactory.getValue()
})
I have changed your plunkr:
spy = jasmine.createSpy('spy');
fac.setValue = spy;
Edit
In Jasmine, mocks are referred to as spies. There are two ways to
create a spy in Jasmine: spyOn() can only be used when the method
already exists on the object, whereas jasmine.createSpy() will return
a brand new function.
Found the information here. The link has a lot more information about creating spies.
As said in the comments, you have absolutely no need for spies to test such a service. If you had to write the documentation for your service: you would say:
setValue() allows storing a value. This value can then be retrieved by calling getValue().
And that's what you should test:
describe('appfactory service',function(){
var appfactory;
beforeEach(module('app'));
beforeEach(inject(function(_appfactory_) {
appfactory = _appfactory_;
}));
it('should store a value and give it back',function() {
var value = 'foo';
appfactory.setValue(value);
expect(appfactory.getValue()).toBe(value);
});
});
Also, your service is not a factory. A factory is an object that is used to create things. Your service doesn't create anything. It is registered in the angular module using a factory function. But the service itself is not a factory.
I've found several posts that shows this code as a way to do async unit testing:
The service:
angular.module('miservices', [])
.service('myAppServices', ['$http', 'httpcalls', function($http, httpcalls) {
this.getAccountType = function(){
return httpcalls.doGet('http://localhost:3010/...').then(function(data){
return data;
}, function(error){
...
});
};
...
The test:
describe('testing myAppServices', function(){
beforeEach(module('smsApp'));
it('should handle names correctly', inject(function(myAppServices){
myAppServices.getAccountType()
.then(function(data) {
expect(data).equal({...});
});
...
We're using AngularJS, Mocha, Chai and we have Sinon installed.
The test never gets to the .then part, but why?
Thanks!
If you are testing your service I would recommend to mock your "httpcalls" service (as that is outside scope in this test).
To mock it you can have several ways, one approach would be to have a mocks module that you use only with your unit tests.
angular.module('miservices.mocks', [])
.service('httpcalls', ['$q', function($q) {
this.returnGet = '';
this.doGet = function(url) {
return $q.when(this.returnGet);
};
};
And your unit test then would be something like:
describe('testing myAppServices', function(){
beforeEach(function() {
module('smsApp');
module('miservices.mocks');
});
it('should handle names correctly', inject(function(myAppServices, httpcalls){
httpcalls.returnGet = 'return data';
myAppServices.getAccountType()
.then(function(data) {
expect(data).equal('return data');
});
...
Because we are inserting the mocks module after application module, httpcalls service gets overwritten by its mock version and allows us to test properly myAppServices without further dependencies.
I wish to reuse my mocks instead of having to set them up in every unit test that has them as dependency. But I'm having a hard time figuring out how to inject them properly.
Here's my attempt at unit test setup, which of course fails because ConfigServiceMockProvider doesn't exist.
describe('LoginService tests', function () {
var LoginService;
beforeEach(module('mocks'));
beforeEach(module('services.loginService', function ($provide, _ConfigServiceMock_) {
$provide.value("ConfigService", _ConfigServiceMock_);
/* instead of having to type e.g. everywhere ConfigService is used
* $provide.value("ConfigService", { 'foobar': function(){} });
*/
});
beforeEach(inject(function (_LoginService_) {
LoginService = _LoginService_;
});
}
ConfigServiceMock
angular.module('mocks').service('ConfigServiceMock', function() {
this.init = function(){};
this.getValue = function(){};
}
I realize I probably could have ConfigServiceMock.js make a global window object, and thereby not needing to load it like this. But I feel there should be a better way.
Try something like this:
describe('Using externally defined mock', function() {
var ConfigServiceMock;
beforeEach(module('mocks'));
beforeEach(module('services.configService', function($provide) {
$provide.factory('ConfigService', function() {return ConfigServiceMock;});
}));
beforeEach(module('services.loginService'));
beforeEach(inject(function (_ConfigServiceMock_) {
ConfigServiceMock = _ConfigServiceMock_;
}));
// Do not combine this call with the one above
beforeEach(inject(function (_LoginService_) {
LoginService = _LoginService_;
}));
it('should have been given the mock', function() {
expect(ConfigServiceMock).toBeDefined('The mock should have been defined');
expect(LoginService.injectedService).toBeDefined('Something should have been injected');
expect(LoginService.injectedService).toBe(ConfigServiceMock, 'The thing injected should be the mock');
});
});
According to this answer, you have to put all of your calls to module before all of your calls to inject.
This introduces a bit of a catch-22 because you have to have the reference to your ConfigServiceMock (via inject) into the spec before you can set it on the LoginService (done in the module call)
The work-around is to set an angular factory function as the ConfigService dependency. This will cause angular to lazy load the service, and by that time you will have received your reference to the ConfigServiceMock.
I want to make an integration test with real calls to my server, so, I don't want to use the $httpBackend module from angular-mocks, So I try this:
beforeEach(inject(function($rootScope,_MembersDataSvc_){
service = _MembersDataSvc_;
}));
it('test',function(done){
service.me().then(function(){done();});
});
And the service is:
function me() {
return $http
.get('urlBase/me')
.then(meSuccess);
function meSuccess(response) {
return response.data.members[0];
}
}
This never call the $http, it seems that angular-mocks override the $http service an never made the call.
Some ideas?
EDIT 1:
According to this post: http://base2.io/2013/10/29/conditionally-mock-http-backend/
you can make a passThrough for that $http calls that you don't want to mock, so y try this:
var service;
var scope;
var $httpBackend;
beforeEach(inject(function($rootScope,_MembersDataSvc_,_$httpBackend_){
service = _MembersDataSvc_;
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
}));
it('test',function(done){
//this.timeout(10000);
$httpBackend.whenGET(/views\/\w+.*/).passThrough();
$httpBackend.whenGET(/^\w+.*/).passThrough();
$httpBackend.whenPOST(/^\w+.*/).passThrough();
service.me().then(function(response){console.log(response);done();});
scope.$apply();
//service.getDevices(member).then(function(response){console.log(response);done();})
});
But the passThrough is undefined here.
EDIT 2:
I read this post: http://blog.xebia.com/2014/03/08/angularjs-e2e-testing-using-ngmocke2e/, but I supose that is an stanalone test??, I want to run with karma and jasmine.
This is my entire test.
describe('integration test', function () {
beforeEach(function () {
module('MyAngularApp');
});
var service;
var scope;
var $httpBackend;
beforeEach(inject(function($rootScope,_MembersDataSvc_,_$httpBackend_){
service = _MembersDataSvc_;
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
}));
it('test for test',function(done){
$httpBackend.whenGET(/views\/\w+.*/).passThrough();
$httpBackend.whenGET(/^\w+.*/).passThrough();
$httpBackend.whenPOST(/^\w+.*/).passThrough();
service.me().then(function(response){console.log(response);done();});
scope.$apply();
});
});
I recomend using ngMidwayTester that allows you to connect to the real backend, I use it to make integration tests on the code level - so something in between unit and e2e testing:
Two types of tests in AngularJS (plus one more) - Full-Spectrum Testing with AngularJS and Karma