zoukankan      html  css  js  c++  java
  • [XState] Using global actions prop for testing

    Let's say we have a State Machine Model:

    import { createMachine, interpret } from "xstate";
    
    const elBox = document.querySelector("#box");
    
    const setPoint = (context, event) => {
      // Set the data-point attribute of `elBox`
      // ...
      elBox.dataset.point = `${event.clientX} - ${event.clientY}`;
    };
    
    const machine = createMachine(
      {
        initial: "idle",
        states: {
          idle: {
            on: {
              mousedown: {
                // Add your action here
                // ...
                target: "dragging",
                actions: [setPoint],
              },
            },
          },
          dragging: {
            on: {
              mouseup: {
                target: "idle",
              },
            },
          },
        },
      }
    );
    
    const service = interpret(machine);
    
    service.onTransition((state) => {
      elBox.dataset.state = state.value;
    });
    
    service.start();
    
    elBox.addEventListener("mousedown", (event) => {
      service.send(event);
    });
    
    elBox.addEventListener("mouseup", (event) => {
      service.send(event);
    });

    We have inline action for 'idle' state when mousedown event happen, it call 'setPoint' function.

    Question is how to test those actions get triggered in Unit testing?

    We can use global 'actions' prop to override existing inline function:

    const machine = createMachine(
      {
        initial: "idle",
        states: {
          idle: {
            on: {
              mousedown: {
                // Add your action here
                // ...
                target: "dragging",
                actions: [setPoint],
              },
            },
          },
          dragging: {
            on: {
              mouseup: {
                target: "idle",
              },
            },
          },
        },
      },
      {
        actions: {
          setPoint: () => {
            console.log("set point");
          },
        },
      }
    );

    Now it will only response with console log. That can be used in Unit testing with some ENV case switcher.

  • 相关阅读:
    牛客编程巅峰赛S1第8场
    【杭电多校4】2020 Multi-University Training Contest 4
    2020牛客暑期多校训练营(第七场)
    DFS【搜索1】
    2020牛客暑期多校训练营(第六场)
    2020牛客暑期多校训练营(第五场)
    大数模板
    分布式前后端分离项目开发步骤
    Linux 查看服务器硬件信息
    写在前面
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13348168.html
Copyright © 2011-2022 走看看