【问题标题】:Wrap jest mocks in a function for use in multiple tests将 jest mocks 包装在一个函数中以用于多个测试
【发布时间】:2020-10-28 10:49:22
【问题描述】:

我正在尝试将 jest.mock 包装到一个函数中,以便可以在多个文件中重复使用它。我的用例是反应钩子,我正在使用打字稿。目前我的测试文件看起来像这样:

test.tsx

//some imports

jest.mock('../path/to/hoook/whatever', () => ({
    useWhatever: jest.fn()
}))


const mockResult = () => {
    return ({
        some stuff
    };
};


describe('Component', () => {
let wrapper;

    beforeEach(() => {
        mocked(useWhatever).mockClear();

        mocked(useWhatever).mockImplementation(() => mockResult);

        wrapper = shallow(
            <Component />
        );
    });

    //tests below
});

这工作得很好,但是这个钩子会被其他组件使用,我正在尝试包装 jest.mock 以便在其他测试中重用。我正在尝试做的事情看起来像这样:

mocks.ts

export const mockWhatever = () => jest.mock('../path/to/hoook/whatever', () => ({
    useWhatever: jest.fn()
}))


export const mockResult = () => {
    return ({
        some stuff
    };
};

test.tsx

//some imports
mockWhatever();

describe('Component', () => {
let wrapper;

    beforeEach(() => {
        mocked(useWhatever).mockClear();

        mocked(useWhatever).mockImplementation(() => mockResult);

        wrapper = shallow(
            <Component />
        );
    });

    //tests below
});

以这种方式执行此操作时,在运行测试时会出现“TypeError: utils_1.mocked(...).mockClear is not a function”之类的错误。是否可以像这样包装模拟?如果是这样,我可能做错了什么或遗漏了什么?

谢谢

【问题讨论】:

  • Mocked 是 ts-jest 库的一部分。
  • 我明白了。您可以发布整个 test.tsx,包括导入吗?它们在这里是相关的。

标签: reactjs typescript unit-testing jestjs ts-jest


【解决方案1】:

jest.mock 是上面使用 Babel 转换导入的 hoisted,这就是它按预期工作的原因:

import ... from 'whatever';
jest.mock('whatever', ...);

如果没有自定义 Babel 转换,mockWhatever 不可能实现相同的效果,因此模块在被模拟之前被导入。 import 需要替换为 require 并且为了使模拟生效,import..require syntax 可用于 TypeScript 类型安全。

__mocks__ 是一种重用 Jest 提供的模块模拟​​的方法。考虑到有 __mocks__/whatever.js 模拟模块,它与 jest.mock('whatever') 一起用作模拟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2021-03-03
    相关资源
    最近更新 更多