gpt4 book ai didi

reactjs - 如何在 redux 工具包中模拟存储

转载 作者:行者123 更新时间:2023-12-04 03:47:34 25 4
gpt4 key购买 nike

import React from 'react';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import { render, screen, fireEvent } from '@testing-library/react';
import MyApp from './MyApp ';

const initialState = {};
const mockStore = configureStore(initialState);

describe('<MyApp />', () => {
it('click button and shows modal', () => {
render(
<Provider store={mockStore}>
<MyApp />
</Provider>
);

fireEvent.click(screen.getByText('ADD MIOU'));
expect(queryByText('Add MIOU Setting')).toBeInTheDocument();
});
});
我正在使用 jest 和 redux 工具包 reactjs ,并尝试模拟商店来编写测试。
但得到以下错误
类型错误:store.getState 不是函数
有没有什么办法解决这一问题?我错过了什么吗?

最佳答案

我假设您正在尝试测试连接的组件,并且您希望 (1) 运行 Action 创建器和 reducer 以及 (2) 作为测试的一部分更新 redux 状态?
我没有使用过 redux-mock-store,但我在 their documentation 上看到了以下注释,这让我相信这个库可能不会像你期望的那样工作:

Please note that this library is designed to test the action-related logic, not the reducer-related one. In other words, it does not update the Redux store.


建议你试试 this approach用于测试连接的组件。我已经使用这种方法编写了更新 redux 状态和呈现连接组件的测试。
首先,您覆盖 RTL render方法:
// test-utils.js
import React from 'react'
import { render as rtlRender } from '@testing-library/react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
// Import your own reducer
import reducer from '../reducer'

function render(
ui,
{
initialState,
store = createStore(reducer, initialState),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}

// re-export everything
export * from '@testing-library/react'
// override render method
export { render }
然后你直接引用新的渲染方法而不是 RTL。您还可以为您的测试提供初始状态。
import React from 'react'
// We're using our own custom render function and not RTL's render
// our custom utils also re-export everything from RTL
// so we can import fireEvent and screen here as well
import { render, fireEvent, screen } from '../../test-utils'
import App from '../../containers/App'

it('Renders the connected app with initialState', () => {
render(<App />, { initialState: { user: 'Redux User' } })

expect(screen.getByText(/redux user/i)).toBeInTheDocument()
})
(所有代码复制自 redux.js.org 。)

关于reactjs - 如何在 redux 工具包中模拟存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64925842/

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