Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Jasmine JavaScript Testing - toBe vs toEqual


อาร์เรย์สามารถเปรียบเทียบได้ 2 แบบ

  • อ้างอิงถึงออบเจ็กต์อาร์เรย์เดียวกันในหน่วยความจำ

  • อาจอ้างอิงถึงออบเจ็กต์ต่างกันแต่เนื้อหาเท่ากันทุกอย่าง

ตัวอย่าง: toBe (ตรวจสอบ Reference)

สำหรับกรณีที่ 1 Jasmine มีเมธอด toBe สำหรับตรวจสอบ Reference ตัวอย่างเช่น

describe("Array Equality", () => {    it("should check for array reference equality", () => {       let arr = [1, 2, 3];       let arr2 = arr       // ผ่าน       expect(arr).toBe(arr2);       // ล้มเหลว เพราะ reference ไม่เท่ากัน       expect(arr).toBe([1, 2, 3]);    }); });

ผลลัพธ์

1) Array Equality should check for array equality Message:    Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().

ตัวอย่าง: toEqual (Deep Comparison)

สำหรับกรณีที่ 2 เราสามารถใช้เมธอด toEqual เพื่อเปรียบเทียบลึก (deep compare) ตัวอย่างเช่น

describe("Array Equality", () => {    it("should check for array reference equality", () => {       let arr = [1, 2, 3];       let arr2 = arr;       // ผ่าน       expect(arr).toEqual(arr2);       // ผ่าน       expect(arr).toEqual([1, 2, 3]);    }); });

ผลลัพธ์

1 spec, 0 failures