[data-reveal]{opacity:1!important;transform:none!important}
DocumentationTesting

Testing

Test AntelopeJS modules with the built-in test runner. Configure the test environment, write isolated tests, and check interface implementations.

Run the tests

Test the behavior that consumers depend on, through the public interface. The CLI loads the modules that your test configuration lists and runs Mocha tests. The example below tests the in-memory user directory from Exporting Interfaces, so it needs no database.

The CLI runs the tests with the Mocha that the module installs, so add it to the module's development dependencies first:

terminal
npm install --save-dev mocha
ajs module test

To run one test file instead of the whole suite, pass it with -f. The CLI resolves the path from the current directory, and you can repeat -f for more files.

terminal
ajs module test -f test/user-service.test.js

The runner starts the configured modules, runs the selected tests, and then stops the modules. It does not compile your module or your test files. Configure the module's build command as shown below. The first test is JavaScript, so it needs no TypeScript test loader.

Test configuration

To point your module to a test configuration file, add the test field to the antelopeJs section of package.json. Without it, ajs module test fails with Module <name> has no test configuration.

package.json json
{
  "antelopeJs": {
    "test": "antelope.test.ts"
  }
}

List the module under test in this file, along with every provider it needs. Pointing antelopeJs.test at the file does not add the module to the runtime.

antelope.test.ts typescript
import { defineConfig } from "@antelopejs/interface-core/config";

export default defineConfig({
  name: "my-module-test",
  modules: {
    "my-module": {
      source: {
        type: "local",
        path: "./",
        installCommand: "pnpm exec tsc",
      },
    },
  },
  test: {
    folder: "test",
  },
});
FieldDescription
modulesAll modules to load, including the module under test
test.folderDirectory that holds the test files. The default is test.
test.setupAsync function that runs before the tests. It can return configuration overrides.
test.cleanupAsync function that runs after all tests complete

setup runs before the modules load. Use it to start disposable services and return the connection settings that the modules need. It cannot call an interface that those modules have not implemented yet. To seed data, use a Mocha before hook, which runs after startup.

The runner merges the overrides into the loaded configuration. An entry under modules is read as in antelope.config.ts:

  • An object for a module the configuration already declares is merged into its entry, so give only the fields you change. config merges key by key.
  • An entry for a new module can be a version string, which loads the npm package of that name, or an object. A new entry that gives only a source gets an empty config, no importOverrides and no disabledExports.
  • A version string for a module the configuration already declares replaces its whole entry.
  • importOverrides can be a list or a map of interface names to module names.
  • disabled: true leaves the module out.
  • A field set to undefined keeps its loaded value. The exception is a module's config, which reaches the module as undefined.

The run stops with an error that names the field when an override gives a field the wrong type, such as cacheFolder: 42, modules: null or importOverrides: "@scope/x". It stops the same way when the overrides replace the test.setup or test.cleanup hook. The cleanup hook of the configuration file still runs.

Failed assertions still lead to module teardown and cleanup. An error during teardown can stop the cleanup hook from running. Give disposable services their own way to shut down, and do not rely on that hook as your only safeguard.

The runner works in this order:

  1. setup
  2. Module load
  3. construct
  4. start
  5. Tests
  6. destroy
  7. cleanup

Keep the resources that setup creates reachable from cleanup, and make cleanup work after a partial setup.

Test file conventions

Test discovery searches the test folder and its subfolders for .test.ts, .spec.ts, .test.js, and .spec.js files. Discovery does not compile anything. For TypeScript tests, set up a compatible loader, or compile the tests first and point test.folder at the compiled output. Do not let discovery scan both the source and the compiled copies.

text
my-module/
├── test/
│   ├── user-service.test.js
│   ├── auth.test.js
│   └── helpers/
│       └── fixtures.ts
└── antelope.test.ts

The runner does not run helper files and fixtures that do not match the test pattern. You can import them from your test files to share setup logic or test data.

Stub mode

After the modules start, the runner turns on stub mode. A call that has no attached implementation then fails at once, instead of waiting for an implementation to attach.

  • An InterfaceFunction call rejects with "Interface function called without implementation in test environment" unless a loaded module provides the implementation.
  • RegisteringProxy.register() throws the same error if no module handles the registration.

As a result, your test configuration must load every module the tests need. Each dependency is declared up front, so tests stay isolated and give the same result on every run.

Warning

If a test fails with "Interface function called without implementation in test environment", check that the modules section of your test configuration lists the module that provides that interface.

Write a test

Create this CommonJS test in the module directory. It calls the compiled public interface of the user-directory example and uses the Node.js built-in assertions, so it needs no assertion library.

test/user-service.test.js javascript
const assert = require("node:assert/strict");
const { GetUser, CreateUser, DeleteUser } = require("../dist/interface");

describe("User Service", () => {
  it("creates, retrieves and deletes a user", async () => {
    const user = await CreateUser("Alice", "[email protected]");
    const retrieved = await GetUser(user.id);
    assert.equal(retrieved.name, "Alice");
    assert.equal(retrieved.email, "[email protected]");

    await DeleteUser(user.id);
    await assert.rejects(GetUser(user.id), /User not found/);
  });
});

Run ajs module test from the module root. One test passes. The read assertions fail if the provider returns the wrong data. The rejection after deletion fails if delete does nothing. Both assertions go through the public contract, not through the private map that stores the users.

Note

The test runner uses Mocha. Any assertion library that throws on failure works with it, such as Chai or the Node.js built-in assert.

Interface tests

A standalone interface package can ship its own tests in a tests/ directory. These tests define the expected behavior of the contract, and every module that implements the interface must pass them.

text
@your-org/interface-email/
├── src/
│   ├── index.ts              # Interface contract
│   └── tests/
│       └── send.test.ts      # Contract tests
└── dist/
    └── tests/
        └── send.test.js      # Compiled tests

When you run ajs module test on an implementing module, the runner also finds and runs these interface tests. It reads the implements array from the module's package.json, resolves each interface package, and collects the compiled test files in its dist/tests/ directory. It then runs the interface tests together with the module's own tests.

text
Test execution order:
1. Local tests from the module's test/ directory
2. Interface tests from each package listed in implements

The interface author writes the suite once, and each provider runs it against its implementation. A passing suite proves compatibility only for the behaviors it checks, not for every use of the contract. The runner skips an interface suite that is missing or that it cannot resolve. Read the list of tests that ran, and do not take a passing run with no interface tests as proof that the provider is compatible.

Note

Passing -f turns off automatic discovery, including the interface suites. Run ajs module test without -f before you publish a provider.

Each test and hook has 2000 ms by default, interface suites included. A provider whose setup is slower, such as one that starts a database, raises it for the whole run with ajs module test --timeout <ms>.

Tip

When you create a standalone interface package, include tests that check the contract behavior. These tests are a compliance suite that every module claiming to implement the interface must pass.

Implementation-specific tests

A module can have its own tests next to the interface tests. Local tests in the module's test/ directory cover the implementation-specific behavior that the interface contract does not define.

text
my-email-module/
├── test/
│   ├── retry-logic.test.ts     # Implementation-specific
│   └── rate-limiting.test.ts   # Implementation-specific
└── package.json                # implements: ["@your-org/interface-email"]

The test runner collects both sets of test files and runs them in one Mocha session. The interface tests check that the module fulfills the contract. The local tests check the implementation details.

Test with dependencies

When your module depends on interfaces from other modules, list those modules in the test configuration. The test runner loads them and binds every interface before it runs the tests.

The following configuration is a sketch for an application with local auth and database modules. It does not replace the self-contained example above. Keep the module under test in modules, give each provider its real configuration, and build local providers before you load them.

antelope.test.ts typescript
import { defineConfig } from "@antelopejs/interface-core/config";

export default defineConfig({
  name: "my-module-test",
  modules: {
    "my-module": {
      source: { type: "local", path: "./", installCommand: "pnpm exec tsc" },
    },
    "auth-module": {
      source: { type: "local", path: "../auth-module" },
      config: { secretKey: "test-secret" },
    },
    "db-module": {
      source: { type: "local", path: "../db-module" },
      config: { connectionString: "mongodb://localhost/test" },
    },
  },
  test: {
    folder: "test",
    cleanup: async () => {},
  },
});

Each module in the modules section receives its own config object. Use test values, such as a test database URL, mock API keys, or shorter timeouts, so the tests stay fast and never touch production data. Drop the test database in cleanup.

Tip

Keep test configurations small. Load only the modules your tests depend on. Fewer modules start faster and give clearer failure messages.

See also