[MST] Describe Your Application Domain Using mobx-state-tree(MST) Models

In this lesson, we introduce the running example of this course, a wishlist app. We will take a look at the core of mobx-state-tree (MST), models. Models describe the shape of your state and perform type validation.

You will learn:

  • Defining models using types.Model
  • Instantiating models from JSON using Model.create
  • Primitive types: types.string & types.number
  • Type inference for primitive types
  • types.array
  • types.optional
  • Composing models into a model tree
  • Testing models using jest

 

To create a model:

import { types } from "mobx-state-tree"

export const WishListItem = types.model({
    name: types.string,
    price: types.number,
    image: ""
})

export const WishList = types.model({
    items: types.optional(types.array(WishListItem), [])
})

'types' is similar to React PropTypes.

 

Once model is created, then we can write tests to verify:

import { WishList, WishListItem } from "./WishList"

it("can create a instance of a model", () => {
    const item = WishListItem.create({
        name: "Chronicles of Narnia Box Set - C.S. Lewis",
        price: 28.73
    })

    expect(item.price).toBe(28.73)
    expect(item.image).toBe("")
})

it("can create a wishlist", () => {
    const list = WishList.create({
        items: [
            {
                name: "Chronicles of Narnia Box Set - C.S. Lewis",
                price: 28.73
            }
        ]
    })

    expect(list.items.length).toBe(1)
    expect(list.items[0].price).toBe(28.73)
})

 

posted @ 2018-01-23 19:48  Zhentiw  阅读(278)  评论(0编辑  收藏  举报