M
M
mr jeery2018-03-10 22:10:07
JavaScript
mr jeery, 2018-03-10 22:10:07

Testing in React, what's wrong?

I'm starting to deal with testing and ran into a problem, please help.
Why does the test return false?

1 failing

  1) <Balance />
       Balance test:

      AssertionError: expected false to equal true
      + expected - actual

      -false
      +true

Here is the component for which I am going to write a test.
export  class BalanceCont extends React.Component {

   render() {

    const tifOptions = Object.keys(this.props.total).filter(key =>
      this.props.total[key]!='0'
    ).map(key =>
      <div className="balance__list" value={key}><b>{key}</b>: {parseFloat(this.props.total[key].toFixed(5))}</div>
  )


    return(

      <div id="foo" className="balance__cont">

        <h3>Мои балансы</h3>
        {tifOptions}
      </div>
    )


    }
  }

  const mapStateToProps = state => ( { total: (state.total)  } );

  export const Balance = connect(mapStateToProps)(BalanceCont);

Here is a code test:
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import configureStore from 'redux-mock-store';

import {Balance} from '../app/containers/balance/src/balance';

const mockStore = configureStore();


describe('<Balance />', () => {

  let store = mockStore({});

  it('Balance test', function () {

    const wrapper = shallow(<Balance store={store}  />);
    expect(wrapper.contains(<h3>Мои балансы</h3>)).to.equal(true);
  });


});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-03-10
@jeerjmin

At the very least, you get an error when you try to call render : Because you don't pass total to store . Why would you even wrap the component in connect when testing? Try changing the component file like this:

import React from 'react';
import { connect } from 'react-redux';

export class Balance extends React.Component {
  // some code
}

const mapStateToProps = ({ total }) => ({ total });

export default connect(mapStateToProps)(Balance);

What you have named the component BalanceCont is semantically incorrect. Since the container is the HOC on top of your component, by calling connect you are wrapping the component in a container.
Now you can import the component for tests as: And the container in the application as: Modified test:
import React from 'react';
import { shallow, mount } from 'enzyme';
import { expect } from 'chai';
import { Balance } from '../app/containers/balance/src/balance';

describe('<Balance />', () => {
  it('Balance test', function () {
    
    const mockTotal = { /* mock code */ };
    
    const wrapper = shallow(<Balance total={mockTotal} />);
    expect(wrapper.contains(<h3>Мои балансы</h3>)).to.equal(true);
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question