Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@iobroker/testing

AlCalzone35.4kMIT5.0.4TypeScript support: included

Shared utilities for adapter and module testing in ioBroker

iobroker, component-tests, testing

readme

@iobroker/testing

This repo provides utilities for testing of ioBroker adapters and other ioBroker-related modules. It supports:

  • Unit tests using mocks (without a running JS-Controller) deprecated and no longer used
  • Integration tests that test against a running JS-Controller instance.

The unit tests are realized using the following tools that are provided by this module:

  • A mock database which implements the most basic functionality of ioBroker's Objects and States DB by operating on Map objects.
  • A mock Adapter that is connected to the mock database. It implements basic functionality of the real Adapter class, but only operates on the mock database.

Predefined methods for both unit and integration tests are exported.

Usage

Validating package files (package.json, io-package.json, ...)

const path = require("path");
const { tests } = require("@iobroker/testing");

// Run tests
tests.packageFiles(path.join(__dirname, ".."));
//                 ~~~~~~~~~~~~~~~~~~~~~~~~~
// This should be the adapter's root directory

Adapter startup (Integration test)

Run the following snippet in a mocha test file to test the adapter startup process against a real JS-Controller instance:

const path = require("path");
const { tests } = require("@iobroker/testing");

// Run tests
tests.integration(path.join(__dirname, ".."), {
    //            ~~~~~~~~~~~~~~~~~~~~~~~~~
    // This should be the adapter's root directory

    // If the adapter may call process.exit during startup, define here which exit codes are allowed.
    // By default, termination during startup is not allowed.
    allowedExitCodes: [11],

    // To test against a different version of JS-Controller, you can change the version or dist-tag here.
    // Make sure to remove this setting when you're done testing.
    controllerVersion: "latest", // or a specific version like "4.0.1"

    // Define your own tests inside defineAdditionalTests
    defineAdditionalTests({ suite }) {
        // All tests (it, describe) must be grouped in one or more suites. Each suite sets up a fresh environment for the adapter tests.
        // At the beginning of each suite, the databases will be reset and the adapter will be started.
        // The adapter will run until the end of each suite.

        // Since the tests are heavily instrumented, each suite gives access to a so called "harness" to control the tests.
        suite("Test sendTo()", (getHarness) => {
            // For convenience, get the current suite's harness before all tests
            let harness;
            before(() => {
                harness = getHarness();
            });

            it("Should work", () => {
                return new Promise(async (resolve) => {
                    // Start the adapter and wait until it has started
                    await harness.startAdapterAndWait();

                    // Perform the actual test:
                    harness.sendTo("adapter.0", "test", "message", (resp) => {
                        console.dir(resp);
                        resolve();
                    });
                });
            });
        });

        // While developing the tests, you can run only a single suite using `suite.only`...
        suite.only("Only this will run", (getHarness) => {
            // ...
        });
        // ...or prevent a suite from running using `suite.skip`:
        suite.skip("This will never run", (getHarness) => {
            // ...
        });
    },
});

Adapter startup (Unit test)

Unit tests for adapter startup were removed and are essentially a no-op now.
If you defined your own tests, they should still work.

const path = require("path");
const { tests } = require("@iobroker/testing");

tests.unit(path.join(__dirname, ".."), {
    //     ~~~~~~~~~~~~~~~~~~~~~~~~~
    // This should be the adapter's root directory

    // Define your own tests inside defineAdditionalTests.
    // If you need predefined objects etc. here, you need to take care of it yourself
    defineAdditionalTests() {
        it("works", () => {
            // see below how these could look like
        });
    },
});

Helper functions for your own tests

Under utils, several functions are exposed to use in your own tests:

const { utils } = require("@iobroker/testing");

Currently, only utils.unit is defined which contains tools for unit tests:

createMocks()

const { database, adapter } = utils.unit.createMocks();
// or (with custom adapter options)
const { database, adapter } = utils.unit.createMocks(adapterOptions);

This method creates a mock database and a mock adapter. See below for a more detailed description

createAsserts()

const asserts = utils.unit.createAsserts(database, adapter);

These methods take a mock database and adapter and create a set of asserts for your tests. All IDs may either be a string, which is taken literally, or an array of strings which are concatenated with ".". If an ID is not fully qualified, the adapter namespace is prepended automatically.

  • assertObjectExists(id: string | string[]) asserts that an object with the given ID exists in the database.
  • assertStateExists(id: string | string[]) asserts that a state with the given ID exists in the database.
  • assertStateHasValue(id: string | string[], value: any) asserts that a state has the given value.
  • assertStateIsAcked(id: string | string[], ack: boolean = true) asserts that a state is acked (or not if ack === false).
  • assertStateProperty(id: string | string[], property: string, value: any) asserts that one of the state's properties (e.g. from) has the given value
  • assertObjectCommon(id: string | string[], common: ioBroker.ObjectCommon) asserts that an object's common part includes the given common object.
  • assertObjectNative(id: string | string[], native: object) asserts that an object's native part includes the given native object.

MockDatabase

TODO

MockAdapter

TODO

Example

Here's an example how this can be used in a unit test:

import { tests, utils } from "@iobroker/testing";

// Run tests
tests.unit(path.join(__dirname, ".."), {
    //     ~~~~~~~~~~~~~~~~~~~~~~~~~
    // This should be the adapter's root directory

    // Define your own tests inside defineAdditionalTests
    defineAdditionalTests() {
        // Create mocks and asserts
        const { adapter, database } = utils.unit.createMocks();
        const { assertObjectExists } = utils.unit.createAsserts(
            database,
            adapter,
        );

        describe("my test", () => {
            afterEach(() => {
                // The mocks keep track of all method invocations - reset them after each single test
                adapter.resetMockHistory();
                // We want to start each test with a fresh database
                database.clear();
            });

            it("works", () => {
                // Create an object in the fake db we will use in this test
                const theObject: ioBroker.PartialObject = {
                    _id: "whatever",
                    type: "state",
                    common: {
                        role: "whatever",
                    },
                };
                mocks.database.publishObject(theObject);

                // Do something that should be tested

                // Assert that the object still exists
                assertObjectExists(theObject._id);
            });
        });
    },
});

changelog

Changelog

5.0.4 (2025-03-24)

  • Corrected the delState method in the adapter mock

5.0.3 (2025-01-23)

  • Packages were updated

5.0.0 (2024-09-14)

  • Types were migrated to '@iobroker/types' from '@types/iobroker'

4.1.3 (2024-04-17)

  • Allow (deprecated) HTML as admin UI in package tests, so old adapters using HTML UI can still utilize the rest of the package tests

4.1.2 (2024-04-17)

  • Fix: Use shell to spawn npm on Windows to prevent hanging
  • Fix: Duplicate logging of => false when testing if JS controller is running

4.1.1 (2024-03-05)

  • Add support for the new licenseInformation field in io-package.json
  • Add test for the tier field in io-package.json
  • Honor onlyWWW flag in io-package.json

4.1.0 (2022-08-30)

  • Support for specifying the JS-Controller version in integration tests

4.0.0 (2022-08-28)

  • BREAKING: Dropped support for Node.js 12
  • Allow skipping test suites (suite.skip()) and running single test suites (suite.only())

3.0.2 (2022-05-15)

  • Fix: Replace the harness argument to the suite() function with a getHarness() function to avoid accessing a stale harness.

3.0.1 (2022-05-09)

  • BREAKING: The function signature of defineAdditionalTests in integration tests has changed. All user-defined integration tests must now be grouped in one or more suite blocks. The adapter will now only be started at the beginning of each suite. See the documentation for details.
  • BREAKING: The function signature of harness.startAdapterAndWait has changed. It now accepts a boolean as the first parameter which controls whether to wait for the alive state (false) or the info.connection state (true).

2.6.0 (2022-04-18)

  • The loglevel for the adapter and DB instances is now configurable and defaults to "debug" in both cases

2.5.6 (2022-03-05)

  • Allow immediate exit with code 0 for once and subscribe adapters too

2.5.5 (2022-03-04)

  • Allow immediate exit with code 0 for schedule adapters
  • Check that npm is not listed as a local dependency in package.json
  • Updated dependencies

2.5.4 (2022-02-02)

  • Modifying ioBroker databases now uses the same methods that JS-Controller uses internally. This ensures that the testing is compatible with the jsonl database format.
  • Testing adapters with adapter dependencies that try to access the databases during installation now works.

2.5.2 (2021-09-18)

  • Fix: adminUI.config is now respected for the config UI check and JSON config is allowed too
  • Updated dependencies
  • Modernized build process

2.5.1 (2021-09-05)

  • We now use the nightly js-controller dev builds instead of GitHub installation

2.4.4 (2021-03-14)

  • Fix error: iopackContent.common.titleLang is not iterable

2.4.3 (2021-03-12)

  • Fix: The adapter main file now correctly gets located when it is only defined in package.json, not io-package.json

2.4.2 (2021-01-06)

  • Fixed compatibility with the reworked database classes
  • Improved shutdown behavior of the adapter

2.4.1 (2021-01-01)

  • Fixed a bug where the wrong js-controller dependency would be installed

2.4.0 (2020-12-07)

  • Unit tests for adapter startup were removed and only log a warning that you can remove them
  • Upgrade many packages

2.3.0 (2020-08-20)

  • Added missing async functions to adapter mock
  • Fixed: TypeError "Cannot redefine property readyHandler" when using createMocks more than once
  • Upgrade to @types/iobroker v3.0.12

2.2.0 (2020-04-15)

  • Upgrade to @types/iobroker v3.0.2
  • Added mocks for supportsFeature, getPluginInstance, getPluginConfig

2.1.0 (2020-03-01)

  • Integration tests: For Node.js >= 10, the engine-strict flag is now set to true to be in line with newer ioBroker installations

v2.0.2

  • Unit tests: added mocks for getAbsoluteDefaultDataDir and getAbsoluteInstanceDataDir

Sorry, there isn't more yet.