vitest/hoisted-apis-on-top Correctness
作用
要求 hoisted 的 Vitest API (vi.mock、vi.unmock 和 vi.hoisted)出现在文件的顶层。
为什么这不好?
Vitest 在转换期间会将某些 API 提升到文件顶部,因此它们总是会在任何导入之前 运行——无论它们在源码中的什么位置。将它们写在条件语句、测试主体或其他运行时位置中, 可能会造成误导和困惑。
代码看起来像是在运行时执行,但实际上它会最先运行。此规则确保这些被提升的 API 不会出现在令人困惑的上下文中。
示例
此规则的错误代码示例:
js
if (condition) {
vi.mock("some-module", () => {});
}js
if (condition) {
vi.unmock("some-module", () => {});
}js
if (condition) {
vi.hoisted(() => {});
}js
describe("suite", () => {
it("test", async () => {
vi.mock("some-module", () => {});
const sm = await import("some-module");
});
});此规则的正确代码示例:
js
if (condition) {
vi.doMock("some-module", () => {});
}js
vi.mock("some-module", () => {});
if (condition) {
}js
vi.unmock("some-module", () => {});
if (condition) {
}js
vi.hoisted(() => {});
if (condition) {
}js
vi.mock("some-module", () => {});
describe("suite", () => {
it("test", async () => {
const sm = await import("some-module");
});
});如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["vitest"],
"rules": {
"vitest/hoisted-apis-on-top": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["vitest"],
rules: {
"vitest/hoisted-apis-on-top": "error",
},
});bash
oxlint --deny vitest/hoisted-apis-on-top --vitest-plugin版本
此规则在 v1.39.0 中添加。
