Motoko: How to write unit tests?

Hi,

While navigating the CanCan project, I found some unit tests, which is great!
Seems that there’s ic-repl, interesting!

Is there a good read to understand how to properly write unit tests for Motoko? Or maybe share where to learn about the ic-repl

Thank you!

For anyone else interested in writing tests, here’s the repo for ic-repl ( GitHub - chenyan2002/ic-repl ) and has some examples. Also, under testing in the list here GitHub - dfinity/awesome-dfinity: A curated list of awesome projects and resources relating to DFINITY and the Internet Computer

We are still experimenting with the best way to test Motoko and canisters. There are several tools around today that can help with unit testing:

5 Likes

Thank you very much! I’ll test them starting with the ic-repl :slight_smile:

Great response, thanks.

Quick question about ic-repl: I’m guessing we have to make sure to tear down any objects we create in our ic-repl test scripts? I don’t see it done explicitly in any of the examples (unless they are non-stable variables, in which case the next canister deploy should clear out any test data).

ic-repl is testing at the canister level, there are no objects. The script can handle deployment as well, so that the testing script can deploy a new canister, test method calls, and then delete the canister. As an example, see motoko playground’s upgrade test: https://github.com/dfinity/motoko-playground/blob/main/service/pool/tests/upgrade.test.sh

2 Likes

Hm, interesting.

I don’t think I see the canister deletion logic though? I see this:

fail call ic.install_code(
  record {
    arg = encode (init);
    wasm_module = file "../../../.dfx/local/canisters/backend/backend.wasm";
    mode = variant { upgrade };
    canister_id = S;
  },
);

But that seems to upgrade the canister, not delete it.

Right, I don’t need canister deletion in my test. I always start a local replica and create a new canister for the test.

You can call ic.delete_canister to delete the canister if you want.

1 Like