LoginSignup
1
1

Vitest の toBe と toEqual の使い分け

Posted at

はじめに

この記事では、Vitest というテストフレームワークのイコールの判定に利用される expect.toBe()expect.toEqual() の使い分けをサンプルつきで記載していきます。

toBetoEqual の使い分け

オブジェクトのイコール評価時、以下のように使い分けます。

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

image.png

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

image.png

同じインスタンスを参照していれば、イコール判定になります。

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

image.png

補足

単純に 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);
  });
});

image.png

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1