typescript 读取Deno中记录到控制台的值

nc1teljy  于 2023-01-27  发布在  TypeScript
关注(0)|答案(2)|浏览(111)

如何读取Deno中记录到控制台的值?我正在尝试编写一个测试,检查函数是否将正确的值记录到控制台。
我已经尝试过这种方法,但是它只能读取手动键入到stdin.Getting values from Deno stdin中的值

ruarlubt

ruarlubt1#

这更像是一个黑客,但在我的情况下工作

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

rjzwgtxy2#

这是一个很老的问题,但是我在尝试解决类似的问题时偶然发现了它,最后我使用Deno内置的mocking在测试中设置了一个间谍,并检查以确保console.log是用期望的值调用的。

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]
  });
});

相关问题