mercredi 14 mars 2018

jest snapshot testing with redux set props of component

I am trying to render a snapshot of my component and have managed to test that my componentDidMount function is being called and my data is being set as the console.log inside my componentDidMount is showing this when running my test.

When my component loads up, because of the check for this.props.data in my render(), the component in my snapshot returns null. It then loads componentDidMount and sets the data which gets passed to the reducer to update the state. I am trying to render a snapshot showing <one/>, <two/>, <three/>. Is there a way to directly set this.props.data in my situation so that I can bypass and not get into that "if" to render all my child components. Thank you in advance

App Component

 componentDidMount() {
    if (this.props.data === null) {

        this.props.axios.get(`http://localhost:3000/users/123`)
            .then(res => {
                console.log("getting in here and res is :" + res) // {data: is showing}
                this.props.setData(res.data);
            })
    }
}



render() {
       if (this.props.data === null) {
            if (this.props.error) {
                console.log(this.props.error); 
            }
            return null;
        }

        return <div>
            <One oneData={this.props.data.one}/>
            <Two twoData={this.props.data.two}/>
            <Three threeData={this.props.data.three}/>
        </div>
}

in the same component I am dispatching to the reducer which updates the store:

dispatch => ({
    setData: data => dispatch({ type: "LOAD_DATA", dataPayload: data 
})

testfile

import React from "react";
import App from "../../src/components/App";
import reducers from "../../src/reducers";
import { createStore } from "redux";
import { Provider } from "react-redux";
import renderer from 'react-test-renderer';
const store = createStore(reducers);
jest.mock('axios', () => ({
    get: jest.fn()
 }));
import {get} from "axios";
import axios from "axios";

it('renders correctly', async() => {
  const p = Promise.resolve({
       data: {
          "_id" : "123",
          "location" : "LONDON",
       }
  });

  const component = renderer.create(
      <Provider store={store}>
           <App axios={axios}/>
      </Provider>
  );

  console.log(store); 
  let tree = component.toJSON();

  await p;

  console.log("TREE :" + tree); // is returning null
  expect(tree).toMatchSnapshot();

});

Aucun commentaire:

Enregistrer un commentaire