如何使用笑话和酶导入带有模拟数据的手动模拟模块?

时间:2019-07-31 05:43:27

标签: reactjs module mocking jestjs enzyme

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

我在我的React应用程序Auth.js中有一个使用的模块App.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检查后,该测试将从Login模块返回“ Logged-In-False” div。但是,我得到了“真正的”股利。 在测试中,如果我这样做:console.log(wrapper.auth.isLoggedIn()),则返回.isLoggedIn()未定义。

我是React,开玩笑和酶的新手。我不知道出什么问题了,任何帮助都将是很大的!谢谢。

1 个答案:

答案 0 :(得分:0)

解决方案很简单。 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);
})