gpt4 book ai didi

javascript - 如何使用 jest 使用 Promise.all 设置多次提取测试

转载 作者:数据小太阳 更新时间:2023-10-29 03:54:48 31 4
gpt4 key购买 nike

我正在使用 jest 进行测试。我正在使用 react 和 redux,我有这个 Action :

function getData(id, notify) {
return (dispatch, ...) => {
dispatch(anotherFunction());
Promise.all(['resource1', 'resource2', 'resource3'])
.then(([response1,response2,response3]) => {
// ... handle responses
})
.catch(error => { dispatch(handleError(error)); }
};
}

我一直在 Jest 文档中寻找如何为此操作设置测试,但我找不到方法。我试过这样的事情:

it('test description', (done) => {
const expectedActions = [{type: {...}, payload: {...}},{type: {...}, payload: {...}},...];
fetchMock.get('resource1', ...);
fetchMock.get('resource2', ...);
fetchMock.get('resource3', ...);
// ... then the rest of the test calls
});

不成功。那么我应该如何进行呢?

最佳答案

要使用 Promise.all,您可以执行以下操作

test('Testing Stuff', async (done) => {

const expectedActions = [{ foo: {...}, bar: {...} }, { foo: {...}, bar: {...} }];

// we pass the index to this function
const asyncCall = async (index) => {
// check some stuff
expect(somestuff).toBe(someOtherStuff);
// await the actual stuff
const response = await doStuff( expectedActions[index] );
// check the result of our stuff
expect(response).toBe(awesome);
return response;
};

// we put all the asyncCalls we want into Promise.all
const responses = await Promise.all([
asyncCall(0),
asyncCall(1),
...,
asyncCall(n),
]);

// this is redundant in this case, but wth
expect(responses).toEqual(awesome);

done();

});

关于javascript - 如何使用 jest 使用 Promise.all 设置多次提取测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847775/

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