ค้นหาเว็บไซต์

javascript - อ่านค่าที่บันทึกลงคอนโซลใน Deno


ฉันจะอ่านค่าที่ถูกบันทึกในคอนโซลใน Deno ได้อย่างไร? ฉันกำลังพยายามเขียนการทดสอบเพื่อตรวจสอบว่าฟังก์ชันบันทึกค่าที่ถูกต้องไปยังคอนโซลหรือไม่

ฉันได้ลองสิ่งนี้แล้ว แต่มันสามารถอ่านค่าได้เพียงค่าที่พิมพ์ด้วยมือลงใน stdin การรับค่าจาก Deno stdin

คำตอบ #1

นี่เป็นคำถามที่เก่าแก่จริง ๆ แต่ฉันบังเอิญเจอมันตอนพยายามแก้ปัญหาที่คล้ายกัน สุดท้ายฉันก็ใช้การจำลองในตัวของ Deno เพื่อสร้างสปายในทดสอบและตรวจสอบให้แน่ใจว่า console.log ถูกเรียกด้วยค่าที่คาดไว้

import {
  assertSpyCall,
  spy,
} from "https://deno.land/[email /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]
  });
});

คำตอบ #2

นี่เป็นวิธีแก้แบบชั่วคราวแต่ใช้ได้ในกรณีของฉัน

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