Reputation: 3151
How can I read a value logged to the console in Deno? I'm trying to write a test that checks if a function logs the right value to console.
I've already tried this, but it can only read values manually typed into stdin. Getting values from Deno stdin
Upvotes: 2
Views: 793
Reputation: 2156
This is a really old question, but I stumbled across it trying to solve something similar. I ended up using Deno's built in mocking to set up a spy in a test and checking to make sure console.log
was called with the expected value.
import {
assertSpyCall,
spy,
} from "https://deno.land/[email protected]/testing/mock.ts";
function veryImportantLogger(val: string) {
console.log(val)
}
Deno.test("Checks to make sure the right value is logged", () => {
const logSpy = spy(console, "log");
const logValue = "well hello there";
veryImportantLogger(logValue);
assertSpyCall(logSpy, 0, {
args: [logValue]
});
});
Upvotes: 4
Reputation: 3151
This is more of a hack but works in my case
class BinarySearchTree<T> {
// ...
inOrderPrint() {
if (this.left) {
this.left.inOrderPrint();
}
console.log(this.value);
if (this.right) {
this.right.inOrderPrint();
}
}
// ...
}
test("BST: should print elements in order", () => {
let a = [];
const log = console.log;
console.log = x => {
a.push(x);
};
const bst = new BinarySearchTree<number>(1);
bst.insert(8);
bst.insert(5);
bst.insert(7);
bst.insert(6);
bst.insert(3);
bst.insert(4);
bst.insert(2);
bst.inOrderPrint();
console.log = log;
assertEquals(a.join(""), "12345678");
});
Upvotes: 1