使用React和Typescript的Jest手动模拟:模拟E​​S6类依赖

时间:2018-03-28 11:19:16

标签: reactjs typescript react-redux jestjs

我对Jest来说是全新的。

我正在使用React with Typescript,在单元测试中,我必须模拟一个模块,该模块包含在我正在编写单元测试的主文件中(容器组件)。

我尝试测试的文件导入了这个模块:

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

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

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

此文件名为AppPage.component.tsx

测试文件位于同一文件夹中,当我使用自动模拟时,它按预期工作。自动模拟只通过相同导入的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__子文件夹中,我试图将它也放在我要模拟的导入模块的同一文件夹中。 在这两种情况下,它似乎都没有被调用(第一个控制台日志永远不会被打印)。

对我的错误有什么想法吗?

1 个答案:

答案 0 :(得分:4)

我找到了让它发挥作用的方法。

要进行整理,需要执行以下步骤:

  1. 当你嘲笑你的依赖关系时,你可以放置你的__mock__文件夹,或者放在主要文件的同一级别,你要测试哪个文件导入它,或者在同一级别上你要模仿
  2. 在您的单元测试文件中,必须在包含要测试的主文件(需要模拟文件的文件)之前调用jest.mock
  3. 所以,代码如下。

    要进行单元测试的主文件(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
    
相关问题