I was just starting to learn about testing in Motoko, and love the functional aspect of it.
The matchers library works for most cases, but for the case where I’m writing a function that utilizes several other functions or using a third party library, I’d like for the opportunity to mock out those third party libraries, so I can strictly test the unit, or the logic of the top level function that I am writing.
For example, let’s say I’m using a UUID and Time library and want to mock out the implementation of those, so I can control their output.
module.mo
import Time "mo:base/Time";
import Text "mo:base/Text";
import UUID "../src/UUID";
module {
public func createUser(name: Text): MyUserType {
let time = Time.now();
let id = UUID.create();
return {
time: time,
id: id,
name: text
}
}
}
I started playing around with rebinding the functions inside a Module like so
import UUID "../src/UUID";
actor {
public func tryMock(): async () {
UUID.create = func() {
return "1";
};
}
}
And got the error, type error [M0073], expected mutable assignment target
.
This leads me to believe that all declared functions inside a module are immutable. Any declaration of a mutable variable within a module returns the error, type error [M0014], non-static expression in library or module
.
I’ve tried a few other “hacky” approaches, but haven’t been able to rebind or overwrite the module itself so that it is “mocked” in tests.
My questions then are:
- Am I missing something, is mocking at all possible in Motoko?
- Is the intention for mocking/stubbing to not be supported in Motoko, and to prefer other testing patterns?
- What is the recommended way for unit testing this type of scenario? (Hopefully something other than integration testing).