I want to test this flow for my app:
- user logins
- he navigates to certain page and perform some actions which change the page's UI and get persisted in DB
I want to test if these UI changes are really happening/showing up the way it should. I don't see how to do a unit test for this - this seems to me more like an e2e test. However of course I don't want to keep hitting my db server everytime these UI changes occurs, so I need to mock these requests to my server.
I don't quite agree with the approach in
angularjs docs, as it requires to bootstrap my app with a test module. It means either I need to
- change/replace my index.html for a different ng-app, OR
- have an environment variable to distinguish dev/test and bootstrap the correct module.
These approach are not ideal and implying a significant overhead. Therefore I'm experimenting this approach (with karma):
- Similar to the angular docs above, I create a test module (app_test in app_test.js) which requires my original module (app in app.js). This module will do the mocking (with $httpBackend.whenPOST and so on) something like
phones = [{name: 'phone1'}, {name: 'phone2'}];
$httpBackend.whenGET('/phones').respond(phones);
- This app_test.js file will also include a manual bootstrap code like below at the end
angular.element(document).ready(function() {
angular.bootstrap(document, ['app_test', 'app']); //<---------important
});
- I include this app_test.js in my karma config which is to be loaded in the test
- In the original app.js file where my app is initialized, I run some code (in module.run()) to trigger a POST request which is supposed to return the stub data
$http.get('/phones').success(function(data, status, headers) {
console.log('App test post request has returned');
console.log(data);
});
As you can see, the index.html file isn't touched at all, everything is being setup externally to the app. That's why if this works, it is the ideal approach.
But as for the result: When I run this karma test, (probably in initializing phase) these correct stub data is displayed in the console, meaning my mocking was working. However in the real test code within describe() or it(), these mocks request aren't put into play, my requests are being routed to the real server
Can someone please enlighten me on this matter? I have been dwelling into this for few days now. Thanks!