Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularjs Unit Testing: Am I doing it right?
    text
    copied!<p>I started to write unit tests for my angular app. However it seems to me that I use a lot of boilerplate code to init and test the controller.</p> <p>In this Unit Test I want to test if a model from the scope is sent to the Api when I execute a function.</p> <p>I needed 20 lines of code for this. This makes it inconvenient to write unit tests that do only one thing. Do you have any tips on getting the code size to a smaller chunk?</p> <p>This is my current unit test:</p> <pre><code>'use strict'; describe('controllers', function(){ beforeEach(module('kronos')); describe('CustomerSignupCtrl', function() { it('should send customer to Api on submit', inject(function($controller) { var scope = {}; var $location = {}; var Api = { signupCustomer: function(customer) { expect(customer).toEqual({attrs: "customerdata"}); return { success: function() { return this; }, error: function() { return this; } }; } }; var ctrl = $controller('CustomerSignupCtrl', { $scope: scope, $location: location, Api: Api}); scope.customer = {attrs: "customerdata"}; scope.signup(); })); }); }); </code></pre> <p>What I don't like in particular are the following points</p> <ul> <li>I need to init the all dependencies and it doesn't matter if I use them or not</li> <li>The Api returns a promise that I only need because the controller is expecting the promise</li> <li>I need to init the controller.</li> </ul> <p>How can I make this code shorter and more explicit?</p> <p><strong>Edit</strong>: I just noticed I can ignore the <code>$location</code> Service for this unit test. Great <strong>Edit2</strong>: I found out about <a href="https://github.com/angular-app/angular-app" rel="nofollow">angular-app</a>, which serves as a good practice example app. There you can find <a href="https://github.com/angular-app/angular-app/blob/master/client/test/unit/app/admin/users/admin-usersSpec.js" rel="nofollow">specs with jasmine</a>, which are really nice written.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload