Skip to content
← Back to rules

vitest/hoisted-apis-on-top 正确性

An auto-fix is available for this rule.

它做了什么

强制将提升的 API 放在文件顶部。

为什么这是不好的?

某些 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");
  });
});

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "plugins": ["vitest"],
  "rules": {
    "vitest/hoisted-apis-on-top": "error"
  }
}
bash
oxlint --deny vitest/hoisted-apis-on-top --vitest-plugin

参考资料