typescript Enzyme,测试一个使用shallow?的useContext钩子的react组件

7gyucuyw  于 2023-04-22  发布在  TypeScript
关注(0)|答案(2)|浏览(118)

我如何测试我的组件,使用jest和酶与浅和一个React组件,使用useContext挂钩。
如何模拟“pValue.state.fullLang”?

src\Language Select.tsx

import React, { useContext } from 'react';
import { LanguageContext } from './utils/LanguageHook';


function LanguageSelect() {
    const pValue: any = useContext(LanguageContext);

    return (
        <div className="LanguageSelect" data-test="languageSelect-box">
            <div className="languageArea">{pValue.state.fullLang}</div>
        </div>
    );
}

export default LanguageSelect;

src\LanguageSelect.test.tsx

import React from 'react';
import { shallow } from 'enzyme';
import LanguageSelect from './LanguageSelect';

test.only('that the LanguageSelect component exists', () => {

    jest.mock('react', () => {
        const ActualReact = require.requireActual('react');
        return {
          ...ActualReact,
          useContext: () => ({ state: { fullLang: 'mocked context' } }),
      };
    });
    const wrapper = shallow(<LanguageSelect />)

    expect(wrapper.find('[data-test="languageSelect-box"]').exists()).toBeTruthy()
    wrapper.unmount();
})
o4hqfura

o4hqfura1#

如果你是在隔离状态下测试这个组件,那么你可以像这样模拟useContext

jest.mock('react', () => {
    const ActualReact = require.requireActual('react');
    return {
      ...ActualReact,
      useContext: () => ({ state: { fullLang: 'mocked context' } }),
  };
});
icomxhvb

icomxhvb2#

测试包含本地函数但不涉及元素和事件的React函数组件,可以使用Vitest和Enzyme

import React from "react";

function Button({ text }: any) {
  const handleClick = (a: number, b: number) => {
    return a + b;
  };
  return (
    <button>
      {text}
    </button>
  );
}

export default Button;

相关问题