jest/no-hooks 风格
它做了什么
禁止使用 Jest 的设置和清理钩子,例如 beforeAll。
为什么这是个问题?
Jest 提供了用于设置和清理任务的全局函数,这些函数会在每个测试用例和每个测试套件之前/之后被调用。使用这些钩子会促进测试之间的共享状态。
此规则会报告以下函数调用:
beforeAllbeforeEachafterAllafterEach
示例
此规则的 错误 代码示例:
javascript
function setupFoo(options) {
/* ... */
}
function setupBar(options) {
/* ... */
}
describe("foo", () => {
let foo;
beforeEach(() => {
foo = setupFoo();
});
afterEach(() => {
foo = null;
});
it("执行某些操作", () => {
expect(foo.doesSomething()).toBe(true);
});
describe("带有 bar", () => {
let bar;
beforeEach(() => {
bar = setupBar();
});
afterEach(() => {
bar = null;
});
it("对 bar 执行某些操作", () => {
expect(foo.doesSomething(bar)).toBe(true);
});
});
});该规则与 eslint-plugin-vitest 兼容。要使用它,请在您的 .oxlintrc.json 中添加以下配置:
json
{
"rules": {
"vitest/no-hooks": "error"
}
}配置
此规则接受一个包含以下属性的配置对象:
allow
type: string[]
default: []
允许使用的钩子函数名称数组。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"plugins": ["jest"],
"rules": {
"jest/no-hooks": "error"
}
}bash
oxlint --deny jest/no-hooks --jest-plugin