Search code examples
javascripttypescriptconsoledeno

Read value logged to the console in Deno


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


Solution

  • 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");
    });