简体   繁体   中英

Unit testing directives without unnecessary dependencies in module AngularJS

I want to write a test for the directive.

In App

requiresDependencies = ["someModule1","someModule2"];
var app = angular.module('app', requiresDependencies);

In test

describe("Logon Hours Editor", function ()
{
    var compile, rootScope;
    var element;

    beforeEach(module('app'));

    beforeEach(inject(['$compile', '$rootScope', function ($compile, $rootScope)
    {
        compile = $compile;
        rootScope = $rootScope;
        element = $compile('some html')($rootScope);
    } ]
    )); ....

My directive is relative to the main unit, and I do not want to connect other test modules (someModule1,someModule2) described in "requiresDependencies" ,because later their numbers and names can be changed. How do I connect only without his dependencies?

You have to mock them. For example, you can create a module called mocks with ad with the services or directives you want to mock. You then load it with beforeEach(module('mocks')); and your calls from the test suite to whatever service you have in mocks will be using the dummy implementation.

You can put this mock module in your test folder, like /test/lib/my-mocks.js (next to angular-mocks.js, if you're using angular-seed). Lastly, you include it in karma.conf.js :

files = [
  'app/lib/jquery/jquery-1.9.1.js',
  JASMINE,
  JASMINE_ADAPTER,
  'test/lib/jasmine-jquery.js',
  'app/lib/angular/angular.js',
  ...
  'test/lib/myproject/my-mocks.js',
   ...
];

Another approach is using jasmine spies. For example:

 spyOn($location, 'absUrl').andCallFake(function (p) {
     return 'http://localhost/app/index.html#/this/is/my/route';
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM