jakesgordon / javascript-state-machine

A javascript finite state machine library
MIT License
8.69k stars 964 forks source link

Transition from `none` #128

Open cliftonc opened 7 years ago

cliftonc commented 7 years ago

I may be using the library wrong, but am upgrading from 2.x.

Say I have the following (made up) FSM:

{
  init: 'index',
  transitions: [
    { name: 'index', from: '*', to: 'index' },
    { name: 'help', from: '*', to: 'showHelp' }
  ], 
 methods: {
   onIndex: () => { console.log('INDEX') },
   onShowHelp: () => { console.log('SHOW HELP') },
   onEnterState: (lifecycle) => {
          console.log(`Entered state ${lifecycle.to} from state ${lifecycle.from} via event ${lifecycle.transition}`);
   }
 }
}

When I initialise this now I get a transition that didn't used to occur.

Entered state index from state none via event init

This then fires the onIndex method that wouldn't previously have been called until I called fsm.index().

Where this becomes problematic is in my unit tests of the FSM, where I am attempting to initialise the FSM in a specific state and then test the transitions. I want to initialise it in a specific state, as if it was already there, but not have its method fire (as this interferes with the subsequent transition I want to test).

I would assume that initialising something in a state wouldn't fire the lifecycle events to transition to it from none - I don't want this transition, I want it to just be in the state I ask it to be in when I initialise it.

Is there a way to disable the init transition from none? Or am I thinking of unit tests from the wrong angle?

Sebring commented 3 years ago

As the machine is created the 'init' will fire and you will get the 'none' -> 'index' you are seeing. If this is not desired have it start in another state, like init: 'new' and do machine.goto('index').