How to test modules?

Hi everyone. I created modules with, for example:

    const passes_mod = b.createModule(.{
        .source_file = .{ .path = "src/passes/mod.zig" },
        .dependencies = &.{
            .{ .name = "utils", .module = utils_mod },
            .{ .name = "ast", .module = ast_mod },
            .{ .name = "machine_code", .module = machine_code_mod },

How do I run tests of this module? b.addTest doesn’t take in a *Module.

The most common way is to have a test block in the ‘main’ file of the module that references all other files in the module. See the Zig standard library for an example:

Combined with all the pub const blah = @import("blah.zig"); lines in std.zig, it will run all the tests in those files as well when running zig test lib/std/std.zig or addTest with .root_source_file = .{ .path = "lib/std/std.zig" }.

Modules as in the new build system terminology context. How do you link the dependencies in that regard then? zig test lib/std/std.zig cannot resolve the modules (if there is, like “utils” or “ast” in the OP, or you don’t use modules at all like the stdlib). How to do that with addTest?

This is what I’ve been doing:

    const my_tests = b.addTest(.{
        .root_source_file = .{ .path = "src/root.zig" },
        .target = target,
        .optimize = mode,
    my_tests.addModule("utils", utils_mod);
    // other stuff to add a 'run tests' step, etc

and then in src/root.zig:

const std = @import("std");

pub const something = @import("something.zig");
pub const something_else = @import("something_else.zig");
// etc

test {

and src/something.zig:

const std = @import("std");
const utils = @import("utils");

test "something" {
    const result =;
    try std.testing.expect(result);

As you noted, this will make it harder to run using zig test (but not impossible, zig build will end up running zig test with command line arguments to provide the module definitions, you can use --verbose when doing zig build ... to see which commands actually get run)

1 Like

In latest Zig, both b.addTest and b.AddExecutable will return a *Step.Compile, so they share same methods, you can just test.addModule like what you do for exe.