gpt4 book ai didi

reactjs - 在 xstate 中模拟调用的 promise

转载 作者:行者123 更新时间:2023-11-28 21:15:29 25 4
gpt4 key购买 nike

我正在尝试测试在发生状态转换时是否会调用 promise。

我遵循了 the official xState tutorial 中概述的方法但我收到以下错误

超时 - 在 jest.setTimeout.Timeout 指定的 5000 毫秒超时内未调用异步回调

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

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 副作用。我想断言模拟的副作用被调用了。但是我得到了上面列出的错误。

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');
});

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

最佳答案

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

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

应该是

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

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

话虽这么说,但我试过您的示例,发现它有效,就模拟的内容而言,它与您的实现略有不同:

机器.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: {

}
}
});

关于reactjs - 在 xstate 中模拟调用的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59191224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com