用 eslint 开玩笑地模拟对象
Mock object in jest with eslint
假设我有以下代码
export function myFunction(user) {
return transform(user);
)
我创建了一个 __tests__
文件夹,并在其中创建了一个 __mocks__
文件夹 user.mock.ts
其中有
export const user = { id: 1, name: "John" }
现在在我的 __test__
文件夹中,我有 user.spec.ts
import { user } from './__mocks__/user.mock';
describe('user', () => {
it('should map user correctly', () => {
const expected = { id: 1, name: "John" }
const result = myFunction(user);
expect(result).toEqual(expected);
});
});
我有以下eslintrc
{
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"eslint-plugin-jest"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"prettier",
"plugin:jest/recommended"
],
"rules": {
}
}
我收到以下错误
Mocks should not be manually imported from a mocks directory. Instead use jest.mock
and import from the original module
path.eslintjest/no-mocks-import
使用名为 __mocks__
的特殊命名目录的机制是一种能够自动检测包模拟的开玩笑方式(而不是作为放置代码的地方 运行明确地)。
作为测试的一部分,您绝不会在代码中显式导入此文件夹中的文件。
因此,如果您只是为您的案例使用一个普通的文件夹名称,并且不与开玩笑的约定交叉连接,那么您应该能够消除错误。
相比之下,如果您想实际模拟一个现有的包(比如用您自己的 fetch
版本替换 fetch
),那么请参阅 https://jestjs.io/docs/manual-mocks#mocking-node-modules 了解如何构建文件,例如调用 __mocks__/fetch.ts
将 fetch 的实际实现替换为伪造其行为的实现。这是专门命名的目录的唯一用途。
假设我有以下代码
export function myFunction(user) {
return transform(user);
)
我创建了一个 __tests__
文件夹,并在其中创建了一个 __mocks__
文件夹 user.mock.ts
其中有
export const user = { id: 1, name: "John" }
现在在我的 __test__
文件夹中,我有 user.spec.ts
import { user } from './__mocks__/user.mock';
describe('user', () => {
it('should map user correctly', () => {
const expected = { id: 1, name: "John" }
const result = myFunction(user);
expect(result).toEqual(expected);
});
});
我有以下eslintrc
{
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"eslint-plugin-jest"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"prettier",
"plugin:jest/recommended"
],
"rules": {
}
}
我收到以下错误
Mocks should not be manually imported from a mocks directory. Instead use
jest.mock
and import from the original module path.eslintjest/no-mocks-import
使用名为 __mocks__
的特殊命名目录的机制是一种能够自动检测包模拟的开玩笑方式(而不是作为放置代码的地方 运行明确地)。
作为测试的一部分,您绝不会在代码中显式导入此文件夹中的文件。
因此,如果您只是为您的案例使用一个普通的文件夹名称,并且不与开玩笑的约定交叉连接,那么您应该能够消除错误。
相比之下,如果您想实际模拟一个现有的包(比如用您自己的 fetch
版本替换 fetch
),那么请参阅 https://jestjs.io/docs/manual-mocks#mocking-node-modules 了解如何构建文件,例如调用 __mocks__/fetch.ts
将 fetch 的实际实现替换为伪造其行为的实现。这是专门命名的目录的唯一用途。