Search code examples
javascripttestingfunctional-testinginternleadfoot

How do I test a view library in intern.js?


I am building a library which uses backbone as a base. My library has a View class, which is an extension of Backbone.View. It has an HTML Element as a property of it. I have a bunch of new functions on the view and I want to test them with intern.

The problem is that I can't find a way to reference the DOM from intern itself. The only way I can see for this to work is to open up a remote URL of a separate HTML page, and query this DOM with leadfoot. This method seems great for a website where you go to specific pages to test your site, but I am trying to build a library, so it seems unnecessary to have separate pages just to test core features of a library.

Is there a way to test a view library without putting all of your code in dummy html files to open with leadfoot?


Solution

  • Sure, you have a couple of options, both of which involve writing unit tests (not functional tests). One is to run unit tests in a browser directly using Intern's client.html, the other is to run them in a browser using WebDriver (intern-runner).

    Your unit tests will load whatever classes you're trying to test, instantiate a instances of them, make assertions, etc. Since your unit tests will be running in a browser, they'll have access to the DOM.

    Note that your tests won't load test pages, they'll load code modules. So a test might look something like:

    define([
        'intern!object', 'intern/chai!assert', 'app/View'
    ], function (registerSuite, assert, View) {
        var view;
    
        registerSuite({
            name: 'app/View',
    
            afterEach: function () {
                // cleanup the view after each test
                view.remove();
                view = null;
            },
    
            someTest: function () {
                var view = new View();
                // run tests on the view
            }
    });
    

    To run your tests using WebDriver, list it in suites rather than functionalSuites in your intern config, then run Intern in webdriver mode (intern-runner or intern run -w).

    To run your tests in the browser client, start a static server based in your project directory (intern serve if using intern-cli), open a browser, and browse to http://localhost:<port>/node_modules/intern/client.html?config=tests/intern (assuming your test config is at tests/intern.js).