reactjs - 我可以为酶浅渲染中的变量指定一个值吗?
问题描述
我正在尝试在 Enzyme 中为 React 组件编写一个测试,该组件从另一个文件接收具有特定键的对象。我需要代码相信在运行测试套件时已收到该对象。
我想要的输出是一个正在运行的测试套件。我的实际结果是此错误消息:
TypeError: Cannot read property 'user' of undefined
104 | </div>
105 | ) : null}
> 106 | {auth.user ? (
| ^
107 | <SidebarProfile
108 | displayName={auth.user}
109 | username={auth.user}
at Sidebar (src/components/sidebar/sidebar/Sidebar.js:106:31)
at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:829:32)
让我告诉你我是怎么到这里的。
我有一个侧边栏组件。它的内容如下:
import { useAuth } from "../../../auth/use-auth";
function Sidebar(props) {
const auth = useAuth();
return (
<aside id="sidebar">
// ...
{auth.user ? (
<SidebarProfile
displayName={auth.user}
username={auth.user}
profilePic={Logo}
clicked={() => {
setShowModal(true);
}}
/>
) : null}
// ...
</aside>
);
}
export default Sidebar;
当代码真正运行时,有一个用户(我)登录并且代码将auth.user
值更新为用户的用户名。但是在测试套件中,这不会发生。
我要运行的具体测试是:
describe("checking the Sidebar works properly", () => {
const wrapper = shallow(<Sidebar />);
const thinWrapper = shallow(<Sidebar shrink={true} />);
it("renders a logo", () => {
expect(wrapper.find("#sidebar_logo-wide")).toHaveLength(1);
});
it("renders a *thin* logo", () => {
expect(thinWrapper.find("#sidebar_logo-thin")).toHaveLength(1);
});
it("renders 6 buttons", () => {
expect(wrapper.find(SidebarButton)).toHaveLength(6);
expect(thinWrapper.find(SidebarButton)).toHaveLength(6);
});
});
我想他们都遇到了这个问题。
我在 Google 上搜索过“反应酶 ...”之类的内容,然后是“提供一个常数”、“模拟一个常数”、“定义一个值”、“我的渲染中的值不可用”,但没有一个线程处理这个问题。
我想要的可能看起来像在我的测试文件顶部写这个:
const auth = { user: "someUser" }
但我不希望它这么简单。
编辑:我有一个临时的解决方法。我移到const auth = useAuth()
了侧边栏的父组件。然后我把它放回去作为道具。所以现在我可以浅渲染侧边栏const userInfo = { user: "someUser", jwt: "abcdefg" };
作为道具。这是一个好的解决方案,但我真的很想说“嘿酶,你会假装有一个实际上不存在的常数,好吗?”
解决方案
模拟useAuth
如下: -
jest.mock('./useAuth',
() => ({
useAuth: jest.fn().mockReturnValue({user: 'Roly Poly'})
}));
推荐阅读
- python-3.x - 基本的网络爬虫没有输出
- sql - SQL - 查询两个表并过滤掉结果
- javascript - 元素正在从另一个元素中获取属性值
- python - 如何删除 numpy 数组中最小的 n 个数字并跟踪其索引?
- javascript - TypeError:vue.openBlock 不是函数,同时使用自定义节点模块中的 vue 组件
- python - ModuleNotFoundError:没有名为“firebase”的模块
- javascript - 如果不调整大小,超过 window.matchMedia 将不起作用
- elasticsearch - 使用 serilog 和 ILogger 记录到弹性搜索
- winapi - CreateCompatibleBitmap 和 DPI 缩放?
- postgresql - 当我根据创建日期过滤查询集时,Postgres 占用 100% cpu 并且它永远不会结束