Open devsheva opened 3 days ago
Can you please make the example as minimal as possible while still being reproducible? Ideally it should be done in a single file. Please also include any missing deno.json
file and commands run. It's best that no assumptions are made when trying to troubleshoot your issue.
@iuioiua I updated the issue description with a reproducible code
Thank you. For future reference, this is all we needed to be reproducible:
// deno run <script>
import { assertEquals } from "jsr:@std/assert@^0.226.0";
import { stub } from "jsr:@std/testing@^0.225.3/mock";
const myFn = () => "example";
const _internals = { myFn };
using _myFnStub = stub(_internals, "myFn", () => "mockedExample");
assertEquals(myFn(), "mockedExample");
My understanding is that this is expected behavior. This is because stub()
modifies _internals.myFn
, not myFn()
(which is what you're calling). The correct approach is to call a function that uses _internals.myFn()
, as the documentation details.
// deno run <script>
import { assertEquals } from "jsr:@std/assert@^0.226.0";
import { stub } from "jsr:@std/testing@^0.225.3/mock";
const myFn = () => "example";
const _internals = { myFn };
+ function foo() {
+ return _internals.myFn();
+ }
using _myFnStub = stub(_internals, "myFn", () => "mockedExample");
- assertEquals(myFn(), "mockedExample");
+ assertEquals(foo(), "mockedExample");
I agree with that, but the point is that what If I have a method that calls another method, which calls again another method. Basically I need to mock the entire module or at least the implementation of one specific function of that module.
For example what I want to achieve is this behaviour, since I was using Jest before https://jestjs.io/docs/mock-functions#mocking-modules
In most cases, you should only need to mock a single method. Can you please clarify exactly what you're trying to achieve?
I agree again with you. Have you checked the link I sent just to verify? That's what I'm trying to achieve.
Take this simple example:
You have a module method that uses fetch
to call some API. In your test suite, obviously you don't want to hit the real API so you need to mock the fetch API since it's the one doing the real call. This is pretty easy cause you can simply stub the globalThis.fetch
by using deno's stub
. But what about mocking a module function that is called inside another method that you'll use in your tests?
This last example respects your thought about saying that you should only mock a single method. So how do you mock an internal method that is called by a method you're testing? You'd need to stub implementation of one of those
Describe the bug Mocking an exported function doesn't work, cause the mock is not being called, instead the original one is.
Steps to Reproduce
deno.jsonc
my_spec.ts
Result
Expected behavior
It should call the mocked function and return
mockedExample
.Environment