您可以使用自定义渲染函数创建一个辅助测试库,该函数使用上下文包装您的组件,然后从那里导出所有反应测试库方法
- test/lib.jsx
import React from 'react';
import { render as reactRender } from '@testing-library/react';
export * from '@testing-library/react';
export const render = (MyComponent, options) => {
return reactRender(
<AuthProvider>
<SessionProvider>
<AnotherProvider>
<OneMoreProvider>
{MyComponent}
</OneMoreProvider>
</AnotherProvider>
</SessionProvider>
</AuthProvider>,
options
)
}
然后使用这个助手库来导入测试函数而不是@testing-library/react
直接使用
import { render } from 'test/lib'
import MyComponent from './MyComponent';
test("My component", () => {
const { getByTestId, ... } = render(<MyComponent>);
...
});