0

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

Ikechukwu Eze
  • 2,703
  • 1
  • 13
  • 18

2 Answers2

1

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");
});
Ikechukwu Eze
  • 2,703
  • 1
  • 13
  • 18
  • 1
    This is a valid solution. Another possible way to capture is by overwriting `Deno.core.print` which is used internally by all `console` operations. Unfortunately overwriting `Deno.stdout` won't work since `Deno.core.print` is currently independent from `Deno.stdout`. – Kevin Qian Jan 04 '20 at 23:23
0

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/std@0.165.0/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]
  });
});
Matt McClure
  • 2,046
  • 2
  • 18
  • 19