How to mock modules like you can with jest?
With node/jest I was able to mock specific functions from modules using
jest.mock
at the start of the test file. How can I do this in Deno? I have a module which calls a function from another module:
How can I substitute foo
with a mock/stub/fake for the scope of a test file?
2 Replies
In Deno, you can achieve similar functionality to
jest.mock
using the mocking utilities provided in the Deno standard library. The documentation describes two basic mock types: spy
and stub
, along with assertion functions dedicated to these types.
A spy
is a type of object that records every interaction with it, and you can assert an interaction occurred later. A stub
is an object that simulates some predefined behavior.
Here's an example of how you might use a spy
to wrap a function:
In this example, funcs
would be an object exported from my_module.js
that contains the foo
function you want to spy on. You would then import funcs
and bar
into your test file and create a spy on foo
using sinon.spy
.
For stubbing, you can use the stub
function from the Deno standard library's mocking utilities:
In yourcase, you would create a stub for the
foo
function and then use it in your tests. Remember that you would need to export the object containing the foo
function so that you can replace it with a stub in your tests.
Please note that the examples provided here are based on the documentation and may require adjustments to fit the specific structure of your modules and tests. 🦕