> [!date] published: 2025-05-28
## 값 비교
### `.toBe(value)`
[.toBe(value) · Jest](https://jestjs.io/docs/expect#tobevalue)
원시 타입의 값이나, 객체의 참조가 동일한지 확인한다.
내부적으로 `Object.is` 를 호출한다.
---
부동소수점 숫자에는 사용하면 안된다. rounding 때문에 "완전히" 동일한 값이 나오지 않을 수도 있기 때문이다. 부동소수점 숫자를 비교할 때에는 [`.toBeCloseTo(number, numDigits?)`](https://jestjs.io/docs/expect#tobeclosetonumber-numdigits) 를 대신 사용하면 된다.
---
내부적으로 `Object.is` 를 이용해서 참조 동일성만을 비교하지만,
비교가 실패했을 경우에는 깊은 비교를 해서 실제 값이 어떻게 다른지를 보여준다.
하지만 객체가 너무 크고 복잡한 경우에는 오히려 이런 동작이 혼란스러울 수 있게 때문에
실제로 "참조" 만 비교하고자 한다면
아래처럼 직접 Object.is를 호출해서 참조 동일성만을 명확하게 검사하면 된다.
```ts
// 기존 방식
expect(received).toBe(expected);
// 권장 방식 - 참조 동일성만 명확히 검사
expect(Object.is(received, expected)).toBe(true);
```
### `.toEqual(value)`
[.toEqual(value) · Jest](https://jestjs.io/docs/expect#toequalvalue)
객체 인스턴스의 모든 프로퍼티를 재귀적으로 비교한다. (깊은 비교)
내부적으로 `Object.is`를 이용해서 원시 값을 비교한다.
`can1`과 `can2`는 다른 객체이기 때문에 `toBe`가 `false`이지만
모든 프로퍼티가 같은 값을 가지고 있으므로 `toEqual`은 `true`다.
```ts
const can1 = {
flavor: "grapefruit",
ounces: 12,
};
const can2 = {
flavor: "grapefruit",
ounces: 12,
};
describe("the La Croix cans on my desk", () => {
test("have all the same properties", () => {
expect(can1).toEqual(can2);
});
test("are not the exact same can", () => {
expect(can1).not.toBe(can2);
});
});
```
---
undefined 속성, 배열 요소를 검사하지 않는다.
타입 mismatch도 검사하지 않는다.
엄격한 비교가 필요하다면 [`.toStrictEqual`](https://jestjs.io/docs/expect#tostrictequalvalue)을 이용하면 된다.
```ts
const obj1 = { name: "John", age: undefined };
const obj2 = { name: "John" };
test("toEqual", () => {
expect(obj1).toEqual(obj2);
});
test("toStrictEqual", () => {
expect(obj1).not.toStrictEqual(obj2);
});
```
## 타입/상태 검증
### `.toBeNull()` / `.toBeUndefined()`
[.toBeNull() · Jest](https://jestjs.io/docs/expect#tobenull)
`.toBeNull()` 은 `.toBe(null)`과 동일한 기능을 한다.
에러 메시지가 좀 더 명확하다는 차이가 있음
```ts
const notNullValue = "not null";
test("tobe", () => {
expect(notNullValue).toBe(null); // Object.is equality
});
test("toBeNull", () => {
expect(notNullValue).toBeNull(); // Received: "not null"
});
```
---
[.toBeUndefined() · Jest](https://jestjs.io/docs/expect#tobeundefined)
`.toBe(undefined)`와 동일한 기능을 하는 `toBeUndefined()`
하지만 코드 안에서 직접적으로 `undefined`를 참조하지 않는 것이 best practice이다.
```ts
const undefinedValue = undefined;
test("toBe", () => {
expect(undefinedValue).toBe(undefined);
});
test("toBeUndefined", () => {
expect(undefinedValue).toBeUndefined();
});
```
### `toBeTruthy()` / `toBeFalsy()`
- [toBeTruthy() · Jest](https://jestjs.io/docs/expect#tobetruthy)
- [toBeFalsy() · Jest](https://jestjs.io/docs/expect#tobefalsy)
truthy한 값과 falsy한 값 확인하기
```ts
test("truthy and falsy values", () => {
// Truthy
expect("hello").toBeTruthy();
expect(1).toBeTruthy();
expect([]).toBeTruthy();
expect({}).toBeTruthy();
// Falsy
expect("").toBeFalsy();
expect(0).toBeFalsy();
expect(null).toBeFalsy();
expect(undefined).toBeFalsy();
expect(false).toBeFalsy();
expect(NaN).toBeFalsy();
});
```
## 배열/문자열 검증
### `.toContain(item)`
[.toContain(item) · Jest](https://jestjs.io/docs/expect#tocontainitem)
배열이나 문자열에 특정 요소/문자열이 포함되어 있는지를 검증한다.
다른 iterables도 가능하다!
```ts
test("toContain", () => {
const array = ["apple", "banana", "cherry"];
expect(array).toContain("banana");
const message = "Hello, world!";
expect(message).toContain("Hello");
const set = new Set([1, 2, 3]);
expect(set).toContain(2);
});
```
### `.toHaveLength(number)`
[.toHaveLength(number) · Jest](https://jestjs.io/docs/expect#tohavelengthnumber)
해당하는 객체에 length 프로퍼티가 있는지, 그리고 그 값이 value와 동일한지를 확인한다.
array나 string의 크기를 확인할 때 사용.
```ts
test("toHaveLength", () => {
expect([1, 2, 3]).toHaveLength(3);
expect("abc").toHaveLength(3);
expect("").not.toHaveLength(5);
});
```
## 에러, 함수 호출 검증
### `.toHaveBeenCalled()`
[.toHaveBeenCalled() · Jest](https://jestjs.io/docs/expect#tohavebeencalled)
alias: `.toBeCalled()`
mock 함수가 호출되었는지를 확인한다.
### `.toHaveBeenCalledWith(arg1, arg2, ...)`
[.toHaveBeenCalledWith(arg1, arg2, ...) · Jest](https://jestjs.io/docs/expect#tohavebeencalledwitharg1-arg2-)
alias: `.toBeCalledWith()`
mock 함수가 특정 인수로 호출되었는지를 확인한다. 어떤 시점이든 한번이라도 호출되면 된다.
```ts
test("toHaveBeenCalledWith", () => {
const mockFn = jest.fn();
mockFn("first");
mockFn("second");
mockFn("third");
// 어느 시점에든 이 인수로 호출되었는지 확인
expect(mockFn).toHaveBeenCalledWith("second"); // ✅ 성공
expect(mockFn).toHaveBeenCalledWith("first"); // ✅ 성공
expect(mockFn).toHaveBeenCalledWith("never"); // ❌ 실패
});
```
### `.toHaveBeenLastCalledWith(arg1, arg2, ...)`
[.toHaveBeenLastCalledWith(arg1, arg2, ...) · Jest](https://jestjs.io/docs/expect#tohavebeenlastcalledwitharg1-arg2-)
alias: `.lastCalledWith(arg1, arg2, ...)`
mock 함수의 마지막 호출에서 특정 인수가 사용되었는지를 확인한다.
```ts
test("toHaveBeenLastCalledWith", () => {
const mockFn = jest.fn();
mockFn("first");
mockFn("second");
mockFn("third");
// 마지막에 호출된 인자만 확인
expect(mockFn).toHaveBeenLastCalledWith("third"); // ✅ 성공
expect(mockFn).toHaveBeenLastCalledWith("first"); // ❌ 실패
});
```