costa
costa

Reputation: 21

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')
);

Upvotes: 1

Views: 6667

Answers (2)

costa
costa

Reputation: 21

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: ''
};

Upvotes: 1

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

I think it should be state.articles instead of state.reducer.articles in the mapStateToProps.

Upvotes: 0

Related Questions