Zig test unable to find dependency

I am new to Zig and so far it looks like an amazing language. However, I struggle with finding out how to do some basic things, like tests. What I tried is zig test src/main.zig. That does work, as long as I don’t have dependencies. However when I add a dependency like this:

   exe.addPackagePath("mecha", "deps/mecha/mecha.zig");    

then zig build run finds the dependency correctly. But zig test src/main.zig will throw an error like this:

./src/main.zig:2:11: error: unable to find 'mecha'
const m = @import("mecha");

How to setup this correctly?

test_step.addPackagePath(…);

Thanks! Based on this I tried adding

    const test_step = b.step("test", "Run the tests");
    const tests = b.addTest("src/main.zig");
    tests.addPackagePath("mecha.zig", "deps/mecha/mecha.zig");
    tests.setTarget(target);
    tests.setBuildMode(mode);
    test_step.dependOn(&tests.step);

to build.zig. But the error persists:

$ zig test src/main.zig
./src/main.zig:2:11: error: unable to find 'mecha'
const m = @import("mecha");

you need to invoke tests through the build system so it should be zig build test, all the direct commands (zig run, zig build-exe, zig test, etc) don’t use the build.zig file at all

Also note that it’s zig build test because you called that step test, which is a reasonable choice, but I just want to point out that it’s not hardcoded.

const test_step = b.step("toast", "Run the tests");
// ...

At this point you would have to use zig build toast.

2 Likes

Thanks, sadly I still get the same error:

$ zig build test
./src/main.zig:2:11: error: unable to find 'mecha'
const m = @import("mecha");

Oh I didn’t read the full listing, you have a typo here:

The first argument is the package name so it shouldn’t have .zig in it, which also explains why it doesn’t satisfy the mecha dependency.

1 Like

Awesome now it works, thanks! Somehow I there is no “accept answer” button, maybe I need more reputation or something.

1 Like