'Testing xstate invoke Promise
How do I test an invocation of a promise in xstate. I think since my configuration of the machine always returns a Promise.resolve, the testing path for "error.platform" can never be reached. How do I have to configure the machine so that all tests run successfully.
// config.js
export const config = {
initial: "idle",
states: {
idle: {
invoke: {
src: 'fetchData',
onDone: "success",
onError: "failure",
},
},
success: {},
failure: {},
},
};
// HelloWorld.vue
<template>
<div>
<div v-if="state.matches('idle')" data-testid="idle">Hello</div>
<div v-if="state.matches('success')" data-testid="success">World</div>
<div v-if="state.matches('failure')" data-testid="failure">Noop</div>
</div>
</template>
<script>
/* eslint-disable */
import { useMachine } from "xstate-vue2";
import { createMachine } from "xstate";
import { config } from "./config";
const myMachine = createMachine(config, {
services: {
fetchData: (context, event) => Promise.resolve(),
},
});
export default {
setup() {
const { state, send } = useMachine(myMachine);
return {
state,
send,
};
},
};
</script>
// HelloWorld.specs.js
import { render } from "@testing-library/vue";
import { createMachine } from "xstate";
import { config } from "../../src/components/config";
import { createModel } from "@xstate/test";
import HelloWorld from "@/components/HelloWorld.vue";
import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api';
import "@testing-library/jest-dom";
Vue.use(VueCompositionAPI);
const myMachine = createMachine(config)
.withConfig({
services: {
fetchData: (context, event) => Promise.resolve(),
},
});
myMachine.states.idle.meta = {
test: async (screen) =>
expect(screen.getByTestId("idle")).toBeInTheDocument(),
};
myMachine.states.success.meta = {
test: async (screen) =>
expect(screen.getByTestId("success")).toBeInTheDocument(),
};
myMachine.states.failure.meta = {
test: async (screen) =>
expect(screen.getByTestId("failure")).toBeInTheDocument(),
};
const myModel = createModel(myMachine)
describe("test",() => {
const testPlans = myModel.getShortestPathPlans();
testPlans.forEach((plan) => {
describe(plan.description, () => {
plan.paths.forEach((path) => {
it(path.description, async () => {
await path.test(render(HelloWorld));
});
});
});
});
});
Here is the terminal output:
reaches state: "idle"
✓ via (27 ms)
reaches state: "success"
✓ via done.invoke.(machine).idle:invocation[0] (27 ms)
reaches state: "failure"
✕ via error.platform.(machine).idle:invocation[0] (11 ms)test › reaches state: "failure" › via error.platform.(machine).idle:invocation[0]
TestingLibraryElementError: Unable to find an element by: data-testid="failure"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
