Asynchronously loaded Unit Tests with Jasmine and RequireJS

March 1, 2016, Software Development

The following check list shows how to write JavaScript Jasmine Unit Tests where the tests are asynchronously loaded from AMD modules with RequireJS.

  1. Download the Jasmine source files and extract the lib directory into an empty folder.

  2. Download RequireJS and copy the require.js file into the lib directory.

  3. In the lib/jasmine/boot.js file, remove the env.execute(); call from the window.onload callback.

  4. Create a SpecRunner.html file in the directory root with the HTML content shown below. As you can see, the embedded script loads the defined Unit Test modules and manually calls the previously removed execute() method:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Jasmine Spec Runner</title>
    
        <link rel="shortcut icon" type="image/png" href="lib/jasmine/jasmine_favicon.png">
        <link rel="stylesheet" href="lib/jasmine/jasmine.css">
    
        <script src="lib/jasmine/jasmine.js"></script>
        <script src="lib/jasmine/jasmine-html.js"></script>
        <script src="lib/jasmine/boot.js"></script>
    
        <script src="lib/require.js"></script>
        <script>
            var testModules = ["tests/sample"]; // TODO: List AMD modules which contain Unit Tests
    
            require.config({
                baseUrl: "."
            });
    
            require(testModules, function () {
                jasmine.getEnv().execute();
            });
        </script>
    </head>
    <body>
    </body>
    </html>
    
  5. Define Unit Test modules in the testModules variable.

  6. Run your Unit Tests by navigating to the SpecRunner.html HTML page.

You can find a sample project with this setup on GitHub.

Tweet about this on TwitterShare on FacebookEmail this to someoneShare on TumblrShare on LinkedIn

Tags: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax