Plugin testing

As part of your plugin, you can write automated tests to check that everything works as expected.

These tests run inside the same JavaScript environment as your plugin, so you can call any functions provided by the Platform or your plugin.

Writing tests

Tests are written as JavaScript files inside the test directory in your plugin. The Plugin Tool uploads them to the server, and you use the test command to run them.

Test scripts are run in the JavaScript global context, with the P global set to the plugin under test, and with the plugin’s locals and schema.

You should write one test per file. Each test looks something like this:

t.test(function() {

    // Call a function defined by the plugin
    var result = P.test_function();

    // Check the return value with an assertion
    t.assert(result === 42);

    // Log in as a user
    t.login("user@example.com");

    // Call a request handler with a given parameter
    t.get("/do/example/action", {"target": "1234"});
    
    // Check a value in the view passed to E.render()
    // by the request handler.
    t.assert(t.last.view.name === "Joe Bloggs");

});

Testing is performed through the t global. There’s a little bit of boilerplate code on the first and last lines to use the t.test() function to run your test in the correct environment.

When a test starts, the current user is the privileged SYSTEM user, as no request is active.

The t.login() function logs in a user. You can then call your plugin’s request handlers using functions like t.get() and t.post(). Information about the response is returned from these functions, but your tests may read better if you access it through the t.last property.

To check that a result is correct, use an assert statement. If the assert fails, the test will be aborted and failure reported.

You can use console.log() in your tests while you’re writing them. To see the output, keep the Plugin Tool running the develop command in another window.

Test schema

If you need to apply some extra schema to the application to run the tests, include a test/test.schema file. This declares schema in the same way as a requirements.schema file.

Setup and teardown scripts

If the special script test/_setup.js exists, it will always be run once per test run, before any other test is run. If test/_teardown.js exists, it’ll be run after all other tests have run.

These scripts are intending for setting up test data, and performing any clean up work after the tests have run.

Note that any objects or other changes made by the test scripts are not automatically deleted by the testing framework.

Testing environment

Test runner
Assertions
Testing requests