如何解决开玩笑的 MobX 存储在测试之间没有重置
我有一个简单的登录组件和一个应该保存一些用户信息的 MobX 存储。我想用 Jest 测试这种集成。该应用程序是使用 Create React App 创建的,所以我只是为我的测试构建它。
我的登录组件如下所示:
exports.postme = (req,res) => {
const newRex= {
body: req.body.body,reqType: req.body.reqType,location: req.body.location,};
const BusBoy = require("busboy");
const path = require("path");
const os = require("os");
const fs = require("fs");
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imagetoBeUploaded = {};
busboy.on("file",(fieldname,file,filename,encoding,mimetype) => {
if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
return res.status(400).json({ error: "Wrong file type submitted" });
}
const imageExtension = filename.split(".")[filename.split(".").length - 1];
imageFileName = `${Math.round(
Math.random() * 100000000
)}.${imageExtension}`;
const filepath = path.join(os.tmpdir(),imageFileName);
imagetoBeUploaded = { filepath,mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish",() => {
admin
.storage()
.bucket()
.upload(imagetoBeUploaded.filepath,{
resumable: false,Metadata: {
Metadata: {
contentType: imagetoBeUploaded.mimetype,},})
.then(() => {
const imgurl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
db.collection("requests")
.add(newRequest)
.then((doc) => {
db.doc(`/requests/${doc.id}`).update({ imgurl });
const res = newRex;
res.Id = doc.id;
res.imgurl = imgurl ;
return res.json(newRex);
});
})
.catch((err) => {
res.status(500).json({ error: "Something went wrong" });
console.error(err);
});
});
busboy.end(req.rawBody);
};
我的 RootStore 看起来像这样并提供了 useStores 钩子:
const Login = () => {
const { accountStore,userStore } = useStores();
const { user } = userStore;
return(
<>
{user ?
<>
<h1>{user.fullName}</h1>
<h2>{user.username}</h2>
</>
:
<main className="form-signin">
<Button onClick={accountStore.RedirectToFeide} aria-label='sign-in-with-feide-button'>Sign in with Feide</Button>
<Button onClick={userStore.GetCurrentUser} aria-label='get-info-button'>Get Current User Info</Button>
</main>
}
</>
)
}
export default observer(Login);
如果商店中的用户在场,我想查看他们的信息。如果没有,我希望看到两个按钮。
我在名为 __mocks__ 的文件夹中模拟了 UserStore,如下所示:
export class RootStore {
public userStore: UserStore;
public accountStore: AccountStore;
constructor() {
this.userStore = new UserStore(this);
this.accountStore = new AccountStore(this);
}
}
const StoresContext = createContext(new RootStore());
export const useStores = () => useContext(StoresContext);
当我在测试中使用 jest.mock() 时,GetCurrentUser 方法被正确模拟,并且模拟数据设置在用户对象中。但是,在以任何方式进行新测试之前,我无法重置用户对象。
我试过了:
- 模拟 beforeEach/afterEach
- jest.clearallMocks()、jest.resetAllMocks() 和 jest.restoreAllMocks() 都在 beforeEach 和没有
- 添加和删除描述以隔离测试
测试如下:
class UserStore {
private rootStore: RootStore;
public user?: User;
constructor (rootStore: RootStore) {
makeAutoObservable(this)
this.rootStore = rootStore;
}
@action
GetCurrentUser = async () => {
this.user = {
username: 'username',fullName: 'Test User',dateOfBirth: new Date('1994-03-15'),email: 'test@example.com'
}
}
}
export default UserStore;
由于第一个测试按下按钮并设置用户可观察,第二个测试失败。如何在每次测试之间重置整个模拟存储?
解决方法
尝试在测试文件中包含您正在模拟的钩子的导入。
或
您可以尝试以另一种方式模拟它:在测试中包含 useStores
钩子的导入。然后你调用 jest.mock('useStores')
。然后你应该模拟它的实现。
import useStores from '../../stores/UserStore')
jest.mock('useStores')
useStores.mockImplementation(() => someDummyData)
您可以在 docs 中找到描述的解决方案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。