【问题标题】:How to test a react component that is dependent on useContext hook?如何测试依赖于 useContext 钩子的反应组件?
【发布时间】:2019-07-08 13:29:43
【问题描述】:

我有一个使用useContext 的组件,然后它的输出取决于上下文中的值。一个简单的例子:

import React, { useContext } from 'react';

const MyComponent = () => {
  const name = useContext(NameContext);

  return <div>{name}</div>;
};

在使用 react 和 jest 快照中的浅渲染器测试此组件时。如何更改NameContext 的值?

【问题讨论】:

  • 你可以用&lt;NameContext.Provider&gt;包裹你的组件:github.com/facebook/react/issues/7905
  • 这似乎不适用于浅层渲染,因为那样它就不会渲染我的组件的内部。当我尝试得到如下快照时:&lt;NameContext.Provider value={'Paul'}&gt;&lt;MyComponent/&gt;&lt;/NameContext.Provider&gt; 而不是 &lt;div&gt;Paul&lt;/div&gt;
  • 是的,这里.dive() 是为
  • .dive() 来自酶,但反应浅渲染器没有类似的东西。
  • 是的,你是对的,错过了那部分

标签: reactjs jestjs react-hooks react-test-renderer


【解决方案1】:

一般来说,使用钩子不应该改变太多的测试策略。这里更大的问题实际上不是钩子,而是上下文的使用,这使事情变得有点复杂。

有很多方法可以使这项工作,但我发现与'react-test-renderer/shallow' 一起工作的唯一方法是注入一个模拟钩子:

import ShallowRenderer from 'react-test-renderer/shallow';

let realUseContext;
let useContextMock;
// Setup mock
beforeEach(() => {
    realUseContext = React.useContext;
    useContextMock = React.useContext = jest.fn();
});
// Cleanup mock
afterEach(() => {
    React.useContext = realUseContext;
});

test("mock hook", () => {
    useContextMock.mockReturnValue("Test Value");
    const element = new ShallowRenderer().render(
        <MyComponent />
    );
    expect(element.props.children).toBe('Test Value');
});

不过,这有点脏,而且是特定于实现的,所以如果您能够在使用浅层渲染器上做出妥协,还有其他一些可用的选项:

非浅层渲染

如果你不是浅层渲染,你可以将组件包装在上下文提供程序中以注入你想要的值:

import TestRenderer from 'react-test-renderer';

test("non-shallow render", () => {
    const element = new TestRenderer.create(
        <NameContext.Provider value="Provided Value">
            <MyComponent />
        </NameContext.Provider>
    );
    expect(element.root.findByType("div").children).toEqual(['Provided Value']);
});

(免责声明:这个应该工作,但是当我测试它时,我遇到了一个错误,我认为这是我的设置中的一个问题)

使用 Enzyme 和 Dive 进行浅层渲染

正如@skyboyer 评论的那样,酶的浅层渲染器支持.dive,允许您深度渲染原本浅层渲染组件的一部分:

import { shallow } from "./enzyme";

test("enzyme dive", () => {
    const TestComponent = () => (
        <NameContext.Provider value="Provided Value">
            <MyComponent />
        </NameContext.Provider>
    );
    const element = shallow(<TestComponent />);
    expect(element.find(MyComponent).dive().text()).toBe("Provided Value");
});

使用 ReactDOM

最后,Hooks FAQ 有一个使用ReactDOM 测试钩子的示例,它也可以正常工作。当然,使用ReactDOM 意味着这也是一个深度渲染,而不是浅层渲染。

let container;
beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
});

afterEach(() => {
    document.body.removeChild(container);
    container = null;
});

test("with ReactDOM", () => {
    act(() => {
        ReactDOM.render((
            <NameContext.Provider value="Provided Value">
                <MyComponent />
            </NameContext.Provider>
        ), container);
    });

    expect(container.textContent).toBe("Provided Value");
});

【讨论】:

  • 我喜欢模拟的想法。我没有想到。不像其他方法那么优雅,但比我尝试的方法更优雅。我喜欢deep 函数的想法,我希望他们能在某个时候将它带入浅层渲染器。感谢您的回答!
  • 我在使用 Enzyme 时面临挑战,我完全按照您展示的模拟想法进行操作,但问题是当我检查我的条件组件未使用上下文值呈现时。注意:我使用 useEffect 中的上下文值更新我的组件。
  • 如果value 是一个包含属性和函数的对象。
  • 如果MyComponent 包含一个孩子怎么办?
【解决方案2】:

我尝试使用 Enzyme + .dive,但是在潜水时,它无法识别上下文道具,它会获取默认道具。实际上,这是 Enzyme 团队的一个已知问题。 同时,我想出了一个更简单的解决方案,它包括创建一个自定义钩子,只用你的上下文返回useContext,并在测试中模拟这个自定义钩子的返回:

AppContext.js - 创建上下文。

import React, { useContext } from 'react';

export const useAppContext = () => useContext(AppContext);

const defaultValues = { color: 'green' };
const AppContext = React.createContext(defaultValues);

export default AppContext;

App.js — 提供上下文

import React from 'react';
import AppContext from './AppContext';
import Hello from './Hello';

export default function App() {
  return (
    <AppContext.Provider value={{ color: 'red' }}>
      <Hello />
    </AppContext.Provider>
  );
}

Hello.js - 使用上下文

import React from 'react';
import { useAppContext } from './AppContext';

const Hello = props => {
  const { color } = useAppContext();
  return <h1 style={{ color: color }}>Hello {color}!</h1>;
};

export default Hello;

Hello.test.js - 使用 Enzyme shallow 测试 useContext

import React from 'react';
import { shallow } from 'enzyme';
import * as AppContext from './AppContext';

import Hello from './Hello';

describe('<Hello />', () => {
  test('it should mock the context', () => {
    const contextValues = { color: 'orange' };
    jest
      .spyOn(AppContext, 'useAppContext')
      .mockImplementation(() => contextValues);
    const wrapper = shallow(<Hello />);
    const h1 = wrapper.find('h1');

    expect(h1.text()).toBe('Hello orange!');
  });
});

查看完整的 Medium 文章 https://medium.com/7shifts-engineering-blog/testing-usecontext-react-hook-with-enzyme-shallow-da062140fc83

【讨论】:

  • 我遵循了同样的例子。我看到每次运行测试时都会模拟实际的默认值。模拟值未呈现,请告诉我缺少什么。
【解决方案3】:

或者,如果您在没有安装父组件的情况下单独测试您的组件,您可以简单地模拟 useContext:

jest.mock('react', () => {
  const ActualReact = jest.requireActual('react')
  return {
    ...ActualReact,
    useContext: () => ({ }), // what you want to return when useContext get fired goes here
  }
})

【讨论】:

  • 警告:这将替换useContext everywhere 并因此破坏了也使用useContext 的被测事物的任何部分,例如样式组件。 Alex Andrade 的回答将允许您隔离 哪些 使用您想模拟的 useContext
  • @Chris 你可以检查value.displayName 看看它是否来自StylesContextThemeContext 如果你有useContext: value =&gt; {...} 的材质ui,并相应地返回或保留原始功能。
【解决方案4】:

旧帖子,但如果它对某人有帮助,这就是我的工作方式

import * as React from 'react';
import { shallow } from 'enzyme';

describe('MyComponent', () => {
  it('should useContext mock and shallow render a div tag', () => {
    jest.spyOn(React, 'useContext').mockImplementation(() => ({
      name: 'this is a mock context return value'
    }));

    const myComponent = shallow(
      <MyComponent
        props={props}
      />).dive();

    expect(myComponent).toMatchSnapShot();
  });
});

【讨论】:

    【解决方案5】:

    为了完成上述接受的答案,对于非浅层渲染,我稍微调整了代码以简单地用上下文包围我的组件

    import { mount } from 'enzyme';
    import NameContext from './NameContext';
    
    test("non-shallow render", () => {
        const dummyValue = {
          name: 'abcd',
          customizeName: jest.fn(),
          ...
        }; 
        const wrapper = mount(
            <NameContext.Provider value={dummyValue}>
                <MyComponent />
            </NameContext.Provider>
        );
    
        // then use  
        wrapper.find('...').simulate('change', ...);
        ...
        expect(wrapper.find('...')).to...;
    });
    

    【讨论】:

    • 接受的答案包含非浅层渲染的例子
    • 嗨,如果你仔细看,它并不完全相同(使用 TestRenderer)并且在我尝试时给了我一个错误。因此我分享了这个。
    • 我实现了这个,但它对我不起作用。 wrapper 返回未定义 =/ codesandbox.io/s/react-usecontext-jest-test-9r93g?file=/src/…
    【解决方案6】:

    我所做的是测试是否使用了useContext。在我的例子中,useContext 返回名为 dispatch 的函数。

    在我拥有的组件中:

    const dispatch = useContext(...);
    

    然后在onChange方法里面:

    dispatch({ type: 'edit', payload: { value: e.target.value, name: e.target.name } });
    

    所以开始内测:

      const dispatch = jest.fn();
      React.useContext = (() => dispatch) as <T>(context: React.Context<T>) => T;
    

    然后:

      it('calls function when change address input', () => {
       const input = component.find('[name="address"]');
       input.simulate('change', { target: { value: '123', name: 'address' } });
    
       expect(dispatch).toHaveBeenCalledTimes(1);
      });
    

    【讨论】:

      【解决方案7】:

      在测试中,你需要用“Context Provider”包裹组件。 这是一个简单的例子。

      DisplayInfo 组件依赖于 UserContext。

      import React, { useContext } from 'react';
      import { UserContext } from './contexts/UserContextProvider';
      
      export const DisplayInfo = () => {
       const { userInfo } = useContext(UserContext);
      
       const dispUserInfo = () => {
         return userInfo.map((user, i) => {
          return (
           <div key={i}>
            <h1> Name: { user.name } </h1>
            <h1> Email: { user.email } </h1>
           </div>
          )
        });
       }
      
       return(
        <>
         <h1 data-testid="user-info"> USER INFORMATION </h1>
         { userInfo && dispUserInfo() })
        </>
       }
      
      export default DisplayInfo;
      

      这里是用户上下文提供者。

      import React, {useState, createContext} from 'react';
      
      export const UserContext = createContex();
      
      const UserContextProvider = () => {
       const [userInfo, setUserInfo] = useState([]);
      
       const updateUserInfo = () => {
        setUserInfo([...userInfo, newData]);
       }
      
       const values = {
        userInfo,
        updateUserInfo
       }
      
       return(
        <UserContext.Provider = vlaue={values}>
         {props.children}
        </UserContext.Provider>
       )
      }
      
      export default UserContextProvider;
      

      要测试“DisplayInfo”组件,可能还需要使用“react-router-dom”中的“MemoryRouter”。 这是一个例子-

      import React from "react";
      import { render, screen } from "@testing-library/react";
      import "@testing-library/jest-dom/extend-expect";
      import { DisplayInfo } from "./DisplayInfo";
      import UserContextProvider from "./contexts/UserContextProvider";
      import { MemoryRouter } from "react-router-dom";
      
      describe("DisplayInfo", () => {
       describe("layout", () => {
        it("has header of user info", () => {
         render(
          <UserContextProvider>
           <DisplayInfo />
          </UserContextProvider>,
          { wrapper: MemoryRouter }
         );
         let header = screen.getByTestId('user-info');
         expect(header).toHaveTextContent(/user information/i)
        });
       });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-21
        • 1970-01-01
        • 1970-01-01
        • 2019-12-28
        • 2020-01-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多