Jest / Enzyme在已配置的存储中找不到getState函数

时间:2019-12-18 17:31:22

标签: reactjs redux jestjs react-hooks enzyme

我刚刚开始为我们的应用程序编写测试,并被redux困扰。这就是现在的结构。

测试

import configureStore from 'redux-mock-store';
const initialState = require("./testUtils/testUtils")

const mockStore = configureStore(applyMiddleware(thunk), initialState);
describe('<Link/>', () => {
    test("Renders a link tag", () => {
        const wrapper = shallow(
             <Provider store={mockStore}> <Link href="" /> </Provider>
        ).dive({context: {mockStore}})

        expect(wrapper).toMatchSnapshot()
    })
})

组件

const Link = props => {
    const { href, ...rest } = props
    const absoluteLink = useAbsoluteLink(href)
    return <MaterialLink href={absoluteLink} {...rest} />
}

useAbsoluteLink

export default link => {
    const hostName = useSelector(state => state.pageData.hostName)
    if (typeof link != 'undefined'
        && hostName
        && link.charAt(0) != '#'
        && !/^https?:\/\//i.test(link)
        && !/^\/\//.test(link)
    ) {
        link = hostName + link
    }

    return link
}

错误

● <Link/> › Renders a link tag

    TypeError: Cannot read property 'getState' of undefined

      24 | 
      25 |     test("Renders a link tag", () => {
    > 26 |         const wrapper = shallow(
         |                         ^
      27 |              <Provider strore={mockStore}> <Link href="" /> </Provider>
      28 |         ).dive({context: {mockStore}})
      29 | 

我已经尝试了研究过程中看到的所有内容,但没有任何解决方案。

1 个答案:

答案 0 :(得分:0)

似乎您错过了mockStore调用。从doc开始,从configureStore中获得函数nockStore,您应该再次调用该函数,并将假存储传递给它。

// Initialize mockstore with empty state
const initialState = { pageData: { hostName: 'some-host-name' } }
const store = mockStore(initialState)

产生的store应该传递给Provider