0

I'm currently working on testing my react component where I use react-automata. When I run the test it keeps breaking. The goal is to test my Lights component. I'm using the test function from react-automata called "testStateMachine" because I use a statemachine to run the steps of light switching on a button click.

Here is my code example: https://codesandbox.io/s/statemachine-test-sj3w7

This is the test that fails, with error "Cannot read property 'states' of undefined".

import {testStateMachine} from 'react-automata';
import {Lights, lightMachine } from '../Components/Lights';

test('lights with imported components',()=>{
  testStateMachine({ lightMachine}, Lights);
});

Best regards Kristine

Richard Matsen
  • 20,671
  • 3
  • 43
  • 77
  • Could you give more details on 'keeps breaking'? I can see `Transition: TIMER NextState: undefined` in the console, which looks dubious. Perhaps you can explain what you expect vs what actually happens. – Richard Matsen Dec 29 '19 at 23:19

1 Answers1

0

I got a working test by changing the spec Lights.test.js from this:

import {testStateMachine} from 'react-automata';
import {Lights, lightMachine } from '../Components/Lights';

test('lights with imported components',()=>{
  testStateMachine({ lightMachine}, Lights);
});

to this:

import { testStateMachine, withStateMachine } from 'react-automata';
import { Lights } from '../Components/Lights';
import { lightMachine } from "../Xstate/Lightmachine";

test('lights with imported components', () => {

  const fixtures = {
    initialData: {
      states: {
        'greenText': 'green light',
        'yellowText':'yellow light',
        'redText':'red light'
      }
    }
  }

  const StateMachine = withStateMachine(lightMachine)(Lights)

  testStateMachine(StateMachine, { fixtures });
});

From the example spec react-automata/test/testStateMachine.spec.js you need to build the StateMachine first.

Then, since App supplies props to Lights, use fixtures.initialData to do the same in the test.

The test did not work in CodeSandbox, likely because I did not fork it - but it worked ok on my local machine.

Further note

The library seems to be fussy about the version of Jest. I had to down-grade from 24.9.0 you have in the sandbox to 24.7.1. Not sure why.

Richard Matsen
  • 20,671
  • 3
  • 43
  • 77
  • This helped alot, thank you so much. I have run into another problem. I have one component who has imported a custom react scrollbar (https://www.npmjs.com/package/react-scrollbars-custom). Whenever I run the test, the snapshot from the specific component gives the error ** scroller element was not created. Possibly you haven't provided HTMLDivElement to renderer's `elementRef` function. `const StateMachine = withStateMachine(wizardSelvbetjeningMachine)(WizardSelvbetjening); testStateMachine(StateMachine, { fixtures }); `** – Kristine Kristensen Jan 02 '20 at 08:46