Skip to content
← Back to rules

jest/prefer-mock-promise-shorthand 스타일

🛠️ An auto-fix is available for this rule for some violations.

작동 방식

프로미스를 반환하는 함수의 모크를 다룰 때, Jest는 작성해야 하는 반복 코드의 양을 줄이기 위해 몇 가지 API 심플라이언스 기능을 제공합니다. 가능한 경우 이러한 메서드를 선호해야 합니다.

왜 좋지 않은가?

mockImplementation(() => Promise.resolve()) 또는 mockReturnValue(Promise.reject())와 같은 일반적인 모크 함수를 사용하는 것은 Jest의 전용 프로미스 단축형보다 더 복잡하고 가독성이 떨어집니다. mockResolvedValue()mockRejectedValue()와 같은 단축형 메서드는 더 표현적이며 테스트의 의도를 명확하게 드러냅니다.

예시

이 규칙에 잘못된 코드 예시:

javascript
jest.fn().mockImplementation(() => Promise.resolve(123));
jest.spyOn(fs.promises, "readFile").mockReturnValue(Promise.reject(new Error("oh noes!")));

myFunction
  .mockReturnValueOnce(Promise.resolve(42))
  .mockImplementationOnce(() => Promise.resolve(42))
  .mockReturnValue(Promise.reject(new Error("too many calls!")));

이 규칙에 올바른 코드 예시:

javascript
jest.fn().mockResolvedValue(123);
jest.spyOn(fs.promises, "readFile").mockRejectedValue(new Error("oh noes!"));

myFunction
  .mockResolvedValueOnce(42)
  .mockResolvedValueOnce(42)
  .mockRejectedValue(new Error("too many calls!"));

이 규칙은 eslint-plugin-vitest와 호환됩니다. 이를 사용하려면 다음 구성 정보를 .oxlintrc.json에 추가하세요:

json
{
  "rules": {
    "vitest/prefer-mock-promise-shorthand": "error"
  }
}

사용 방법

구성 파일 또는 명령줄에서 이 규칙을 활성화하려면 다음을 사용할 수 있습니다:

json
{
  "plugins": ["jest"],
  "rules": {
    "jest/prefer-mock-promise-shorthand": "error"
  }
}
bash
oxlint --deny jest/prefer-mock-promise-shorthand --jest-plugin

참고 자료