【问题标题】:How do I Import a manually mocked module with mocked data using jest and enzyme?如何使用 jest 和酶导入具有模拟数据的手动模拟模块?
【发布时间】:2019-12-08 13:43:49
【问题描述】:

我的测试似乎没有在__mocks__/Auth.js 下导入我的手动模拟。

我在我的 React 应用程序 App.js 中使用了一个模块 Auth.js。我试图通过在__mocks__/Auth.js 下制作一个模拟文件来使用手动模拟来模拟该模块。我的__mocks__App.jsAuth.js 处于同一文件级别。

我这里有一个仓库:https://github.com/chaselw/reactTesting

或者我的测试如下:

import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16'
import App from './App';

Enzyme.configure({ adapter: new EnzymeAdapter() });

test('logged in false', () => {
    jest.mock('./Auth.js'); //Trying to get `auth.isLoggedIn() === false`
    const wrapper = mount(<App />);
    console.log(wrapper.debug())
    expect(wrapper.exists("[data-test='Logged-In-False']")).toBe(true);
})

预期的结果是,在对auth.isLoggedIn() 进行if 检查之后,测试会从登录模块返回一个“Logged-In-False”div。但是我得到了“真正的” div。 在测试中如果我这样做:console.log(wrapper.auth.isLoggedIn()),它返回.isLoggedIn() is undefined。

我是 React、jest 和酵素的新手。我不知道出了什么问题,任何帮助都会很棒!谢谢。

【问题讨论】:

    标签: reactjs module mocking jestjs enzyme


    【解决方案1】:

    解决方案很简单。 jest.mock('./Auth.js') 不需要在测试中,而是作为导入位于顶层。

    import React from 'react';
    import Enzyme, { shallow, mount } from 'enzyme';
    import EnzymeAdapter from 'enzyme-adapter-react-16'
    import App from './App';
    jest.mock('./Auth');
    
    Enzyme.configure({ adapter: new EnzymeAdapter() });
    
    test('logged in false', () => {
        //Trying to get `auth.isLoggedIn() === false`
        const wrapper = mount(<App />);
        console.log(wrapper.debug())
        expect(wrapper.exists("[data-test='Logged-In-False']")).toBe(true);
    })
    

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 2021-10-10
      • 2021-01-21
      • 2020-07-04
      • 2021-06-27
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多