jest/prefer-mock-return-shorthand スタイル
何を行うか
関数のモックが単純な値を返す場合、Jest はボイラープレートを減らすためのいくつかの API シュガー関数を提供しています。
なぜ悪いのか
Jest の API シュガー関数を使用しないと、不要なボイラープレートが追加され、テストが読みにくくなります。これらのヘルパーは意図を明確に表現し、エラーを減らし、テストをシンプルかつ保守しやすく保ちます。
例
このルールに違反する誤りのあるコードの例:
js
jest.fn().mockImplementation(() => "hello world");
jest
.spyOn(fs.promises, "readFile")
.mockImplementationOnce(() => Promise.reject(new Error("oh noes!")));
myFunction
.mockImplementationOnce(() => 42)
.mockImplementationOnce(() => Promise.resolve(42))
.mockReturnValue(0);このルールに準拠する正しいコードの例:
js
jest.fn().mockResolvedValue(123);
jest.spyOn(fs.promises, "readFile").mockReturnValue(Promise.reject(new Error("oh noes!")));
jest.spyOn(fs.promises, "readFile").mockRejectedValue(new Error("oh noes!"));
jest.spyOn(fs, "readFileSync").mockImplementationOnce(() => {
throw new Error("oh noes!");
});
myFunction.mockResolvedValueOnce(42).mockResolvedValueOnce(42).mockReturnValue(0);このルールは eslint-plugin-vitest と互換性があります。 使用するには、.oxlintrc.json に以下の設定を追加してください:
json
{
"rules": {
"vitest/prefer-mock-return-shorthand": "error"
}
}使用方法
設定ファイルまたは CLI でこのルールを有効化するには、以下のようにします。
json
{
"plugins": ["jest"],
"rules": {
"jest/prefer-mock-return-shorthand": "error"
}
}bash
oxlint --deny jest/prefer-mock-return-shorthand --jest-plugin