简体   繁体   中英

React Testing library: TypeError: Cannot read property 'articles' of undefined

I'm trying to test my Container using react-testing-library.

const middlewares = [thunk.withExtraArgument({})];
const mockStore = configureMockStore(middlewares);

const storeState = {
 articles: 
    [
        {
            id: "9b565b11-7311-5b5e-a699-97873dffb364",
            title: "jsdhahd",
            body: "jsahdjadshajhd",
            link: "https://www.google.com",
            media: "media.jpg"
        },
    ],
loading: false,
error: ''
};

describe('<Homepage />', () => {
  let store;

  beforeEach(() => {
    store = mockStore(storeState);
});

afterEach(() => {
    store.clearActions();
});

it('should render correctly', () => {
    const container = render(<Provider store={store}>{<Homepage />}</Provider>);

    expect(container).toMatchSnapshot();
});

And I get this error: error

Can anyone help? It seems a problem with mocking the redux store, but I don't know exactly how to solve it. I have in the reducer a initial state with the articles, loading, and error. And in my App.js file I'm wrapping the <App/> with the <Provider store={store}>

export const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>, document.getElementById('root')
);

The error was on the way I was creating the storeState object.

Correct way:

const storeState = {
   reducer: {
      articles: 
        [
         {
            id: "9b565b11-7311-5b5e-a699-97873dffb364",
            title: "jsdhahd",
            body: "jsahdjadshajhd",
            link: "https://www.google.com",
            media: "media.jpg"
        },
       ],
     loading: false,
     error: ''
};

我认为它应该是state.articles而不是state.reducer.articles中的mapStateToProps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM