[MST] Test mobx-state-tree Models by Recording Snapshots or Patches

Testing models is straightforward. Especially because MST provides powerful tools to track exactly how your state changes over time. Track snapshots, action invocations or even patches to verify the correctness of your actions!

In this lesson you will learn:

  • To obtain immutable snapshots of the state using getSnapshot
  • To record snapshots using onSnapshot
  • To store and test modifications over time using onPatch
  • Using Jest's snapshot test feature to verify snapshots and patches
  • That MST can infer the type of a snapshot for you

 

Instead of doing test like:

复制代码
it("can add new items", () => {
    const list = WishList.create()
    list.add(
        WishListItem.create({
            name: "Chesterton",
            price: 10
        })
    )

    expect(list.items.length).toBe(1)
    expect(list.items[0].name).toBe("Chesterton")
    list.items[0].changeName("Book of G.K. Chesterton")
    expect(list.items[0].name).toBe("Book of G.K. Chesterton")
})
复制代码

 

We can use snapshot, a more powerful way to test state:

Using 'getSnaphost' from 'mobx-state-tree' and 'toMatchSnapshot()' from the Jest:

复制代码
it("can add new items", () => {
    const list = WishList.create()
    list.add({
        name: "Chesterton",
        price: 10
    })

    expect(getSnapshot(list)).toMatchSnapshot()

    expect(states).toMatchSnapshot()
})
复制代码

 

We can also use a listener to listen the state changes:

复制代码
it("can add new items", () => {
    const list = WishList.create()
    const states = []
    onSnapshot(list, snapshot => {
        states = [...state, snapshot]
    })

    list.add({
        name: "Chesterton",
        price: 10
    })


    expect(getSnapshot(list)).toMatchSnapshot()

    expect(states).toMatchSnapshot()
})
复制代码

 

Sometimes we might don't need to check the whole state tree, we only change part of state, such as an object's name, then what we can use is 'onPatch' from 'mobx-state-tree':

复制代码
it("can add new items - 2", () => {
    const list = WishList.create()
    const patches = []
    onPatch(list, patch => {
        patches.push(patch)
    })

    list.add({
        name: "Chesterton",
        price: 10
    })

    list.items[0].changeName("Google")

    expect(patches).toMatchSnapshot()
})
复制代码

In the code, we only change the name:

list.items[0].changeName("Book of G.K. Chesterton")

 

Patch snapshot looks like:

复制代码
exports[`can create a wishlist - onPatch toMatchSnapshot 1`] = `
Array [
  Object {
    "op": "replace",
    "path": "/items/0/name",
    "value": "Google",
  },
]
`;
复制代码

The 'path' prop tells which prop on the object has been changed to what.

Therefore it is also easy to do undo redo.

  • onPatch(model, listener) attaches a patch listener to the provided model, which will be invoked whenever the model or any of its descendants is mutated
  • applyPatch(model, patch) applies a patch (or array of patches) to the provided model
  • revertPatch(model, patch) reverse applies a patch (or array of patches) to the provided model. This replays the inverse of a set of patches to a model, which can be used to bring it back to its original state

Link

 

posted @   Zhentiw  阅读(938)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-01-23 [Compose] Isomorphisms and round trip data transformations
2015-01-23 [Bootstrap] 1. container & container-fluid
点击右上角即可分享
微信分享提示