首页 > 其他 > 详细

[XState] Using global actions prop for testing

时间:2020-07-21 00:38:04      阅读:91      评论:0      收藏:0      [点我收藏+]

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.

 

[XState] Using global actions prop for testing

原文:https://www.cnblogs.com/Answer1215/p/13348168.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!