【发布时间】:2025-12-01 22:45:01
【问题描述】:
我使用最新版本的 redux-api-middleware 并且我对文档进行了相同的测试,但是 fetch 模拟不起作用。它向真实服务器发出的请求。
import configureMockStore from 'redux-mock-store'
import { apiMiddleware } from 'redux-api-middleware'
import thunk from 'redux-thunk'
import fetchMock from 'fetch-mock'
import {getUser} from './user'
const middlewares = [ thunk, apiMiddleware ]
const mockStore = configureMockStore(middlewares)
describe('async user actions', () => {
// If we have several tests in our test suit, we might want to
// reset and restore the mocks after each test to avoid unexpected behaviors
afterEach(() => {
fetchMock.reset()
fetchMock.restore()
})
it('should dispatch USER_SUCCESS when getUser is called', () => {
// We create a mock store for our test data.
const store = mockStore({})
const body = {
email: 'EMAIL',
username: 'USERNAME'
}
// We build the mock for the fetch request.
// beware that the url must match the action endpoint.
fetchMock.getOnce(`https://hostname/api/users/`, {body: body, headers: {'content-type': 'application/json'}})
// We are going to verify the response with the following actions
const expectedActions = [
{type: actions.USER_REQUEST},
{type: actions.USER_SUCCESS, payload: body}
]
return store.dispatch(actions.getUser()).then(() => {
// Verify that all the actions in the store are the expected ones
expect(store.getActions()).toEqual(expectedActions)
})
})
})
我使用使用下一个模板来执行操作创建者:
export const USER_REQUEST = '@@user/USER_REQUEST'
export const USER_SUCCESS = '@@user/USER_SUCCESS'
export const USER_FAILURE = '@@user/USER_FAILURE'
export const getUser = () => createAction({
endpoint: 'https://hostname/api/users/',
method: 'GET',
headers: { 'Content-Type': 'application/json' },
types: [
USER_REQUEST,
USER_SUCCESS,
USER_FAILURE
]
})
我使用 redux-api-middleware 3.2.0 和 fetch-mock 9.0.0-beta.2 的版本来执行测试,我使用的是 cypress 4.0.1 的版本。 如果有人可以提供帮助,我会为此感到高兴。 谢谢
【问题讨论】:
标签: reactjs unit-testing testing redux