はじめに
この記事では、Vitest というテストフレームワークのイコールの判定に利用される expect.toBe()
と expect.toEqual()
の使い分けをサンプルつきで記載していきます。
toBe
と toEqual
の使い分け
オブジェクトのイコール評価時、以下のように使い分けます。
-
toBe
: 同じインスタンスである(を参照している)ことの判定 -
toEqual
: 同じプロパティ、同じ値であることの判定(インスタンスは別でもOK)
toEqual
toEqual
を利用した場合、別インスタンスであっても同じプロパティ、同じ値であれば、イコール判定になります。
toBetoEqual.test.ts
import { describe, test } from "vitest";
const stockBill = {
type: "apples",
count: 13,
};
const stockMary = {
type: "apples",
count: 13,
};
const stockTom = {
type: "oranges",
count: 10,
};
describe("compare toBe and toEqual", () => {
test("stocks have the same properties and values", () => {
expect(stockBill).toEqual(stockMary);
});
test("stocks don't have the same values", () => {
expect(stockBill).not.toEqual(stockTom);
});
});
toBe
一方、toBe
を利用した場合、同じプロパティ、同じ値であっても別インスタンスであれば、イコール判定にはなりません。
toBetoEqual.test.ts
import { describe } from "vitest";
const stockBill = {
type: "apples",
count: 13,
};
const stockMary = {
type: "apples",
count: 13,
};
describe("compare toBe and toEqual", () => {
test("stocks are not exactly the same", () => {
expect(stockBill).not.toBe(stockMary);
});
});
同じインスタンスを参照していれば、イコール判定になります。
toBetoEqual.test.ts
import { describe } from "vitest";
const stockBill = {
type: "apples",
count: 13,
};
describe("compare toBe and toEqual", () => {
test("stocks are exactly the same", () => {
const refStock = stockBill;
expect(stockBill).toBe(stockBill);
expect(stockBill).toBe(refStock);
});
});
補足
単純に string や number の値のイコール判定であれば、どちらの関数を利用しても同じ結果になります。
toBetoEqual.test.ts
import { describe } from "vitest";
const stockBill = {
type: "apples",
count: 13,
};
const stockMary = {
type: "apples",
count: 13,
};
describe("compare toBe and toEqual", () => {
test("stocks have the same value (type: string) judging from toBe", () => {
expect(stockBill.type).toBe(stockMary.type);
});
test("stocks have the same value (type: string) judging from toEqual", () => {
expect(stockBill.type).toEqual(stockMary.type);
});
test("stocks have the same value (count: number) judging from toBe", () => {
expect(stockBill.count).toBe(stockMary.count);
});
test("stocks have the same value (count: number) judging from toEqual", () => {
expect(stockBill.count).toEqual(stockMary.count);
});
});