unit testing - How to avoid code duplication in AngularJS Jasmine tests -


i'm part of team that's been working on angularjs quite while , our unit tests consist of files contain both test logic , provider mocks of each component tested element relies on.

this leading more , more code duplication, can recommend angular-ey method whereby maintain test infrastructure, mock controller or service once , able inject mocked service other tests required?

edit code i'm working proprietary example consider have 10 or 15 services retrieve data via http requests, format data in different ways , return data. 1 example might return arrays of data in each file relies on service have initialising code following ( cut down , altered please ignore typos or other mistakes )

mydataservice: {     getdataparsedlikey: {         [{obj1},{obj2}...]     },     getdataparsedlikex: {         [{obja},{objb}...]     } beforeeach(angular.mock.module('mymodule')); beforeeach(angular.mock.inject(function(mydataservice) {     mydataservice = function( functionname ) {         return mydataservice[functionname];     }     spyon(mydataservice).and.callthrough(); }) } 

if looking way not declare same mock codes in every test files, suggest below although i'm not sure angular-way or not.

[1] write code declare mock services below unit test , import after angular-mocks.js

in your-common-mocks.js(you can name file like)

(function(window){     window.mymock = {};     window.mymock.prepare_mocks = function(){         module(function($provide) {             $provide.service('mydataservice', function(){                 this.getdataparsedlikey = function(){                     return 'your mock value';                 };             });         });     }; })(window); 

if use karma, write import file in karma.conf.js.

files: [   ...   '(somedirctory)/angular-mocks.js',   '(somedirctory)/your-common-mocks.js'   ... ] 

[2] use mymock.prepare_mocks function in test files.

describe('some test', function() {      beforeeach(mymock.prepare_mocks);      it('getdataparsedlikey', inject(function(mydataservice){         expect('your mock value', mydataservice.getdataparsedlikey()); 

as result of above, have write mock code just 1 time , share mock code in every test files. hope suggest achieve want.


Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -