Test Model

Testing is crucial for the stability of code. Here's an example using the countModel from Quick Start to demonstrate how to perform unit testing on a Model in Modern.js.

To use the testing feature, you need to first enable it. In the project root directory, execute pnpm run new and make the following selection:

? Please select the operation you want to perform: Enable optional features
? Enable optional features Enable "Unit Testing / Integration Testing" feature

This will enable testing feature support.

Create a new file called count.test.ts with the following code:

import { createStore } from '@modern-js/runtime/testing';
import countModel from './count';

describe('test model', () => {
  it('count value should plus one after add', () => {
    const store = createStore();
    const [state, { add }] = store.use(countModel);

    expect(state).toEqual({ value: 1 });


    expect(store.use(countModel)[0]).toEqual({ value: 2 });

The createStore used here is imported from @modern-js/runtime/testing, which internally uses the configuration of runtime.state to create a store.

In the test case, we create a new store to mount countModel, use store.use to get the State and Actions of countModel. Then, we call the add Action to update the state and assert the updated state value.

Execute the pnpm run test command to trigger the execution of the test case.