Jest Manual Mocks with React and Typescript:模拟ES6类依赖项

2cmtqfgy  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(150)

我正在使用React和Typescript,在单元测试中,我必须模拟一个模块,该模块包含在我正在为其编写单元测试的主文件中(容器组件)。
我尝试测试的文件导入了这个模块:

import PerformancesResultsReader from './../../models/PerformancesResultsReader';

然后它以如下方式使用该模块:

const performancesResultsReader = new PerformancesResultsReader();
performancesResultsReader.read();

此文件名为AppPage.component.tsx
测试文件位于同一个文件夹中,当我使用自动模拟时,它按预期工作。自动mock只需要通过相同导入的jest mock即可实现:

jest.mock('./../../models/PerformancesResultsReader');

这样,所有的方法都返回undefined
现在我正试图添加一个手动模拟而不是自动模拟。
以下是PerformancesResultsReader.js模拟代码:

console.log('including mock!');

const mock = jest.fn().mockImplementation(() => {
    return {
        read: () => {
            console.log('mocked');
        }
    };
});

export default mock;

我试着把它放在__mocks__子文件夹中,与我正在测试的文件处于同一级别,我试着把它也放在我想要模拟的导入模块的同一文件夹中。在这两种情况下,它似乎根本没有被调用(第一个控制台日志从来没有被打印出来)。
请问我做错了什么?

mv1qrgav

mv1qrgav1#

我已经找到了解决的办法。
有几个步骤需要整理出来:
1.在模拟依赖项时,可以将__mock__文件夹放置在要测试的主文件的同一级别(该主文件导入了__mock__),或者放置在要模拟的类的同一级别
1.在单元测试文件中,对jest.mock的调用必须在包含要测试的主文件之前发生,主文件要求模拟该文件
代码如下:
待进行单元测试的主文件(AppPage.component.tsx):

// all imports
import PerformancesResultsReader from './../../models/PerformancesResultsReader'; // dependency to be mocked

// your AppPage component here
export default AppPage;

__mock__子文件夹(PerformancesResultsReader.tsx)中进行模拟:

class PerformancesResultsReader {
    constructor() {
        console.log('Mock constructor');
    }
    // all your methods here
}

export default PerformancesResultsReader;

最终单元测试(AppPage.component.spec.tsx):

// call the defined mock
jest.mock('./../../models/PerformancesResultsReader');
// import the main file which is going to be tested
import AppPage from './AppPage.component';

describe('App Container Component', () => {
    // your tests
});

以上示例的文件夹结构如下:

- components
-- AppPage.component.tsx
-- AppPage.component.spec.tsx
- models
-- PerformancesResultsReader.tsx
-- __mock__
--- PerformancesResultsReader.tsx

相关问题