I have a method that triggers an external binary. For testing, I would like to mock the specific Deno.Command()
call and control the values “returned” from the external command. How can I mock methods on the Deno object?
This solution is based on one of the Deno.Command()
examples in the Deno documentation:
This is an example of code I want to test:
export async function testme() {
const command = new Deno.Command(Deno.execPath(), {
args: [
"eval",
"console.log('Hello'); console.error('world')",
],
});
const { code, stdout } = await command.output();
console.assert(code === 0, 'exit code is 0');
return new TextDecoder().decode(stdout);
}
testme().then(
(output) => {
console.log('Done! Got: ' + output);
}
)
If I save that as script.js
I can run it with deno run -A script.js
and get the expected output.
This seems to work as a corresponding test for this method:
import { Buffer } from "node:buffer";
// the tested method
import { testme } from "./script.js";
import { stub } from "https://deno.land/[email protected]/testing/mock.ts";
import { assertEquals } from "jsr:@std/assert@1";
Deno.test("fake command", async function () {
const stubbedCommand = stub(Deno, "Command", function (path, args) {
console.log({path, args});
return {
output: () => {
return Promise.resolve({
code: 0,
stdout: Buffer.from("Foo"),
stderr: Buffer.from("world"),
});
},
};
});
assertEquals(await testme(), "Foo");
stubbedCommand.restore();
});
and I can run the test using deno test -A script.test.js
.