1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「AssertionError: expected { id: 1, title: '掃除', …(2) } to be { id: 1, title: '掃除', …(2) } // Object.is equality」の解決方法【Vitest】

1
Posted at

はじめに

vitestでテストを書いていたところエラーが発生しました。

問題

AssertionError: expected { id: 1, title: '掃除', …(2) } to be { id: 1, title: '掃除', …(2) } // Object.is equality

If it should pass with deep equality, replace "toBe" with "toStrictEqual"

Expected: { id: 1, title: '掃除', …(2) }
Received: serializes to the same string

解決方法

マッチャーをtoBeからtoStrictEqualに変更しました。

todoUsecase.test.ts
describe("updateTodo", () => {
  test("更新したtodoが返ってくる", async () => {
    const id = 1;
    const completed = true;
    const mockDataForUpdate = {
      id: id,
      title: "掃除",
      completed: completed,
      createdAt: new Date().toISOString(),
    };
    const useCase = new TodoUseCase(mockPort);
    const updated = await useCase.updateTodo(id, completed);
-   expect(updated).toBe(mockDataForUpdate);
+   expect(updated).toStrictEqual(mockDataForUpdate);
  });
});

toBeは中身ではなく参照を比較します。
toStrictEqualは中身を比較します。

コード例

const a = { id: 1 };
const b = { id: 1 };   // aと同じ中身だが、別に作ったオブジェクト

expect(a).toBe(b);            // 失敗(別のオブジェクトなので)
expect(a).toStrictEqual(b);   // 成功(中身が同じなので)

おわりに

テストを書くのが久しぶりで忘れていました。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?