Keep karma test data DRY

We used to include mock test data with our Karma test code. When you build up a large body of complex tests the test data setup can run to hundreds of lines. It can be hard to read and understand.
Oftentimes the same data is needed across many unit test suites and is repeated.

Our solution is to create a /mock-data folder and put into it js files with mock json data for common json objects used by our unit tests e.g. customer object.

When we call an expectGET() then we return a copy of the mock data
e.g.
 $httpBackend.expectGET('/api/...../').respond(angular.copy(CUSTOMER_MOCK_DATA));

If you build your mock test data well you can cover multiple tests with one mock data definition. For test cases that need unique combinations I find that I just copy the mock data object and then tweak select properties as necessary in the test or within a block of tests.
e.g.  var myDeCustomer = angular.copy(CUSTOMER_MOCK_DATA);
        myDeCustomer.profile.locale = "de-de";


Important: in your karma config file be sure to load the mock data before the tests that use it in karma files:[] list property
e.g. put this before the unit tests
 '../test/unit/mock-data/**/*.js',


This simple technique can save a lot of effort and also makes the unit test files easier to understand now you don't have to wade through tens/hundreds of lines of data setup.

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more