gpt4 book ai didi

javascript - 用 jest 测试 React 中的异步方法

转载 作者:行者123 更新时间:2023-12-03 14:32:17 25 4
gpt4 key购买 nike

我是单元测试的新手,我有 2 个文件:

RestaurantReducer

import * as Const from '../constants/Const'

const RestaurantReducer = (state = {
restaurantList: []
}, action) => {
switch (action.type) {
case Const.GET_RESTAURANT_LIST: {

return {
...state,
restaurantList: action.payload
};
}
}
return state;
};

export default RestaurantReducer;

和 RestauntActions.js

export function getRestaurantList() {
return dispatch => {
axios({
method: "GET",
url: URLS.URL_RESTAURANT_LIST
}).then((response) => {
dispatch({
type: CONST.GET_RESTAURANT_LIST,
payload: response.data
})
})
}
}

和我的测试:

describe('request reducer', () => {

it('Default values', () => {
expect(restReducer(undefined, {type: 'unexpected'})).toEqual({
restaurantList: []
});
});

// ---------------- Dont know how to check this -------------------
it('Async data',async () => {

expect(restReducer(undefined, {
type: 'GET_RESTAURANT_LIST',
})).toEqual({
...state,
restaurantList: []
});
});
});

我不知道该怎么办。您可以检查来自服务器的连接或数据吗?这样的数据可以模拟吗?但它们是动态的。

最佳答案

您需要模拟依赖项的基本思想(在本例中为 axios 调用)。 This answer describe how to do that .

我创建了示例来说明这个想法:

const axios = require('axios')
const assert = require('assert')
const moxios = require('moxios')


const asyncFunctionToTest = () => {
// grabs length of google page body
return axios({
url: 'http://google.com',
method: 'GET'
})
.then(resp => resp.data.length)
}



describe('async function', () => {
beforeEach(function () {
// import and pass your custom axios instance to this method
moxios.install()
})

afterEach(function () {
// import and pass your custom axios instance to this method
moxios.uninstall()
})
it('returns propper body length', () => {
const BODY = 'short string'
const mocked = moxios.wait(function () {
const request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: BODY
})
})
return Promise.all([asyncFunctionToTest(), mocked]) // imported bit: you need to return promise somehow in your test
.then(([result]) => {
assert(result === BODY.length, result)
})
})
})

关于javascript - 用 jest 测试 React 中的异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46197111/

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