Git Product home page Git Product logo

ng-directive-testing's Introduction

Testing directive – the easy way

Directives in AngularJS encapsulate all of the custom DOM manipulation that happens in an AngularJS application. This makes them very crucial part of a bigger Angular app. DOM manipulation is often source of problems, especially when it comes to browser inconsistencies. This is why it is important to cover the directive code with automated tests. Unfortunately many developers consider any kind of DOM manipulation to be too hard to test so this code more often than not lives a sad life of untested code full of creepy bugs.

The goal of this example is to show how to test directives easily and become confident that the directive code works and works on all targeted browsers.

Let’s take the tabs component from angular homepage.

It would be difficult to test the visual representation of the component, but there are many functional aspects of this component that are worthy testing, for instance:

  • Does it render correct structure (e.g. navigation and content for each pane)?
  • Does the binding inside the content work?
  • Does clicking the particular tab link cause changing of the active pane?
  • Is the first tab selected by default?

Check out the tests at https://github.com/vojtajina/ng-directive-testing/blob/start/test/tabsSpec.js

Executing these tests is easy, we just ask for $compile and compile given DOM structure. Then, we can use jQuery to assert, whether the component works as expected.

Note, that we don’t append the DOM structure to the document. That makes the tests faster, because browser does not have to render it. So unless it’s necessary (eg. you need to know some computed property of some DOM element), don’t attach nodes to the document.

The spectrum of tests is not discrete, there are not just unit tests or e2e tests. The previous tests are probably not unit tests, these are little bit higher level tests. It’s always good to try to cover stuff with as low as possible test. So in this example, we might actually extract the tabs controller and test it separately.

Yep, in this case, it’s just duplicating - we already covered this functionality in the higher level tests above. But now, once we have this little framework for testing the controller separately, we can easily add more tests. For instance, if we found a bug in the controller, we would add a lightweight unit test just for the controller, instead of the entire directive.

This was nice, but how about external templates ? Inlining html templates as strings is kind of nasty (eg. you don’t get syntax highlighting and linting in IDE), so we want to put the templates into external html files. How do you test that? You want to test these html files as well, otherwise it makes no sense. Well, with Karma this is pretty easy - you can use html2js preprocessors for that.

Now, whenever you change any of the html files, Karma immediately generates the js file, that puts the html into $templateCache.


Install Karma

npm install -g karma

Start Karma

karma start

ng-directive-testing's People

Contributors

dtwen avatar vojtajina avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-directive-testing's Issues

karma error: Uncaught SyntaxError: Unexpected token <

C:\Users\owner\Documents\GitHub\ng-directive-testing [master]> karma start karma.conf.js
WARN [karma]: Port 9876 in use
WARN [karma]: Port 9100 in use
INFO [karma]: Karma server started at http://localhost:9877/
INFO [launcher]: Starting browser Chrome
INFO [karma]: To run via this server, use "karma run --runner-port 9101"
INFO [Chrome 26.0 (Windows)]: Connected on socket id d5i-aG6rs-VWa4-YmdAq
Chrome 26.0 (Windows) ERROR
Uncaught SyntaxError: Unexpected token <
at C:/Users/owner/Documents/GitHub/ng-directive-testing/tpl/pane.html:1
Chrome 26.0 (Windows): Executed 0 of 0 ERROR (0.965 secs / 0 secs)

Here it is with PhantomJS as the test browser instead of Chrome, if that makes any never-you-mind:

PhantomJS 1.9 (Windows) ERROR
SyntaxError: Parse error
at C:/Users/owner/Documents/GitHub/ng-directive-testing/tpl/pane.html:1
PhantomJS 1.9 (Windows): Executed 0 of 0 ERROR (1.166 secs / 0 secs)

I see the code at https://github.com/karma-runner/karma-ng-html2js-preprocessor but I have no idea how to integrate it into your example.

Thank you.

Unit Test Karma Jasmine SyntaxError: Parse error on "&" Angular Directive binding

I get SyntaxError: Parse error at my directive line where I want to use a "&" one-way binding from a parent directive's method

myApp.directive('datasourceDeleteBtn', [function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<a href="#">&#x2715</a>',
        scope: {
            datasourceIndex: '@',
            removeParentDiv: '&'
        },
        link: link
    };

    function link(scope, element, attr) {

        element.bind('click', function(event) {
            event.preventDefault();
            scope.deleteDatasource(scope.datasourceIndex);
        });

        // Notify parent directive
        scope.deleteDatasource = function(datasource_index) {
            // conditional stuff that happens not included
            // {} required for passing values to "&" parent scope method
            scope.removeParentDiv({datasource_index});
        };
    }
}]);

HTML

<parent-div ng-repeat> // this is just a mockup not literal
<datasource-delete-btn datasource-index="{{$index}}" remove-parent-div="removeParentDiv()"></datasource-delete-btn>
</parent-div>

The parent div of the ng-repeat that passes removeParentDiv

// parentDiv directive has this
        scope.datasources = [];
        scope.removeDatasourcePicker = function(index) {
            scope.datasources.splice(index, 1);  // ie take it out
        };

It seems the problem is that Jasmine does not like the { }. Removing the brackets results in the test going through (with typical errors since & requires {}).

templateUrl testing

Hi Vojta,

Nice work on Karma, i'm enjoying using it so thanks. Could you give an example of testing directives which use templateUrl please?

I'm using jasmine-jquery. Would you recommend using jasmine.getFixtures or to use.

module(<template-path>)

I've not got either of these solutions working yet.

Getting illegal token error

On windows getting an illegal token error when running the tests.

Uncaught SyntaxError: Unexpected token 
ILLEGAL at C:/zend/Apache2/htdocs/GitHub/ng-directive-testing/tpl/pane.html.js:3

I basically downloaded the repo and then just ran

karma run

I'm guessing this might be an issue with the $compile function?

Using two-way binding on the directive attributes fails in testing

This might be a bug in angular itself, but you might know the problem given we used the same setup as you did for tabs directives.

If we use two-way data binding on the pane directive's attributes (name: '=', title: '=') while it still works in the browser, the attributes are not picked up when run in the test environment using Angular Mock. Looking at a break in the link function, the scope is aware of its variables, but has null values for them. Using name: '@', title: '@' works fine in both environments.

Bug in Angular? Angular Mock? Something specific to this configuration?

Thanks!

When templateUrl and actual file location are different

Hi!

In my application I have a template that lives here:
app/views/angular/my_template.html

In my directive I load the template via:

templateUrl: '/angular/my_template.html'

This difference is due to the way Rails routes and loads templates.

My karma.conf.js includes:

files = [
  JASMINE,
  JASMINE_ADAPTER,
  // Angular Libs
  'vendor/assets/javascripts/angular.js',
  'spec/javascripts/lib/angular/angular-mocks.js',
  // jQuery
  'vendor/assets/javascripts/jquery/jquery-1.9.1.js',
  // Application Code
  'app/assets/javascripts/angular/**/*.js',
  // Test Files
  'spec/javascripts/controllers/**/*_spec.js',
  'spec/javascripts/directives/**/*_spec.js',
  // templates
  'app/views/angular/*.html'
];

preprocessors = {
  'app/views/angular/**/*.html': 'html2js'
};
........

In my directive test I load template module:

beforeEach(module('app/views/angular/my_template.html'));

However, I get an error:
Error: Unexpected request: GET /angular/my_template.html

If I change the templateUrl to:

templateUrl: 'app/views/angular/my_template.html'

the tests work great. I can make my app serve this url so the actual directive will work but it deviates from the norm.

Is there a way to to handle this different is routing vs file location? Am I missing somehting or is directive testing not meant to handle this situation?

Thanks!

-Ryan

getting error [launcher] Error: SyntaxError: Unexpected token . while running protractor test

I am getting following error

Starting selenium standalone server...
[launcher] Running 1 instances of WebDriver
Selenium standalone server started at http://10.158.61.26:65203/wd/hub
[launcher] Error: SyntaxError: Unexpected token .
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)

The version details used are as follows
"npm": "3.8.0",
"node": "5.7.1",
protractor : 3.1.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.