【发布时间】:2020-01-29 16:15:01
【问题描述】:
我正在尝试使用 Mobx 商店和 Jest 和 React-testing-library 来测试我的 React 组件。
问题是我不知道如何注入我的商店进行测试。
这是我的简化代码。
StaffInfo.js(组件)
import React, { useState } from "react";
import { observer, inject } from "mobx-react";
const StaffInfo = props => {
const store = props.instituteStore;
const [staffs, setStaffs] = useState(store.staffs);
return (
<div>
....
</div>
);
}
export default inject(rootStore => ({
instituteStore : rootStore.instituteStore
}))(observer(StaffInfo));
index.js(根存储)
import LoginStore from "./LoginStore";
import InstituteStore from "./InstituteStore";
class RootStore {
constructor(){
this.loginStore = new LoginStore (this);
this.instituteStore = new InstituteStore(this);
}
}
export default RootStore;
InstituteStore.js(目标商店)
import { observable, action } from "mobx";
class InstituteStore {
constructor(root){
this.root = root;
}
@observable
staffs = [];
}
export default InstituteStore;
StaffInfo.test.js(测试文件)
import React from "react";
import ReactDom from "react-dom";
import { MemoryRouter } from "react-router-dom";
import { Provider } from "mobx-react";
import StaffInfo from "./StaffInfo";
import InstituteStore from "../stores/InstituteStore";
describe("Staff Component testing", () => {
test("should be rendered without crashing", () => {
const div = document.createElement("div");
ReactDOM.render(
<MemoryRouter initialEntries={["/staff"]}>
<StaffInfo instituteStore={RootStore.instituteStore} />
</MemoryRouter>,
div
);
ReactDOM.unmountComponentAtNode(div);
});
});
运行此测试文件后,错误消息如下:
TypeError : Cannot read property 'staffs' of undefined
请告诉我代码的哪些部分是错误的。 提前非常感谢!
【问题讨论】:
-
在您的 app.js 中使用
Providerfrommobx-react将 mobx 商店传递给深度嵌套的孩子 -
感谢您的评论,但我已经在我的 app.js 中使用了
Provider。我是否必须在测试中声明 app.js 才能通过商店? -
在尝试了几件事之后,我终于发现我的测试文件中声明的代码如
<Provider {...root} ><App><StaffInfo /></App>运行良好。你拯救了我的一天。非常感谢
标签: reactjs jestjs mobx react-testing-library