0

我正在尝试测试发生状态转换时是否调用了承诺。

我遵循了官方 xState 教程中概述的方法,但出现以下错误

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout

这是我的状态机,它所做的只是在您从初始状态转换时调用一个承诺。

export const statsMachine = Machine(
  {
    id: 'stats',
    initial: 'incomplete',
    states: {
      incomplete: {
        on: {
          MODAL_OPENED: 'loading',
        },
      },
      loading: {
        invoke: {
          id: 'setRatioDefaultsInFirebase',
          src: (context, event) => setStatDefaults(event.payload && event.payload.userId),
          onDone: {
            target: 'modal',
          },
          onError: {
            target: 'incomplete',
          },
        },
      },
      modal: {...}
    }
  })

这是我的测试。我想模拟我的 api 调用,而不是像教程中那样触发真正的 api 调用。我用笑话来模拟副作用。我想断言模拟的副作用被调用了。但我得到了上面列出的错误。

jest.mock('../statsAPI');

test('stats should start off with minimum ratios', done => {
      setStatDefaults.mockResolvedValueOnce();

      const statsBoxService = interpret(statsMachine)
        .onTransition(state => {
          if (state.matches({ selected: 'modal' })) {
            expect(setStatDefaults).toHaveBeenCalled();
            done();
          }
        })
        .start();

      statsBoxService.send('MODAL_OPENED');
    });

我必须更改什么才能断言我的模拟副作用在机器转换时被调用?

4

1 回答 1

1

我认为这可能就像您的 if 语句错误一样简单:

if (state.matches({ selected: 'modal' })) {

应该

if (state.matches('modal')) {

在示例中,'initial'、'loading'、'loaded'、'failed' 是状态 'selected' 的子级

话虽这么说,我玩弄了你的例子,发现这很有效,它与你的实现在模拟方面略有不同:

machine.test.ts:

import { interpret } from 'xstate';
import { statsMachine } from './machines';

test('stats should start off with minimum ratios', done => {

  global.fetch = jest.fn().mockImplementation(
    () => Promise.resolve({ json: () => Promise.resolve({}) })
  );

  const statsBoxService = interpret(statsMachine)
    .onTransition(state => {
      if (state.matches('modal')) {
        expect(global.fetch).toHaveBeenCalledTimes(1);
        done();
      }
    })
    .start();

  statsBoxService.send('MODAL_OPENED');
});

机器.ts:

import { Machine } from 'xstate';

export const setStatDefaults = async (t: any) => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  return response.json();
};

export const statsMachine = Machine(
  {
    id: 'stats',
    initial: 'init',
    states: {
      init: {
        on: {
          MODAL_OPENED: 'loading',
        }
      },
      incomplete: {
        on: {
          MODAL_OPENED: 'loading',
        }
      },
      loading: {
        invoke: {
          id: 'setRatioDefaultsInFirebase',
          src: (context, event) => setStatDefaults(event.payload && event.payload.userId),
          onDone: {
            target: 'modal',
          },
          onError: {
            target: 'incomplete',
          },
        },
      },
      modal: {

      }
    }
  });
于 2019-12-05T12:22:35.293 回答