0
votes

I'm trying to test this component method:

componentWillMount() {
    if (this.props.location.query.customerId) {
      const customer = _.find(this.props.customers.data, ['id', this.state.customerId]);
      this.props.dispatch(getTransactionReceipts(this.props.user, this.state.dateRange));
      this.props.dispatch(setVisibilityFilter({customerId: customer.id,}, 'filter'));
      this.props.dispatch(getCustomers(this.props.user)).then(() => {
        this.props.dispatch(setCustomer(customer));
      });
    }
    else {
      this.loadData(this.props);
      if (this.props.location.query.receiptId) {
        let receiptId = this.props.location.query.receiptId;
        this.props.dispatch(setVisibilityFilter(receiptId));
      }
      else {
        this.props.dispatch(setVisibilityFilter({property: 'type', value: 'All Transactions'}, 'filter'));
      }
    }
  }

but I get this error when I run the test: TypeError: Cannot read property 'id' of undefined

I know it's because the customer.id part, but I don't know how to mock that and make it accessible to the test.

Here's what I have:

  beforeEach(function () {
    stubs = {};
    stubs.dispatch = sinon.stub();
    stubs.windowOpen = sinon.stub();
    stubs.handleFilterSelection = sinon.stub();
    stubs.handleVoidClose = sinon.stub();
    stubs.processCreditCardVoid = sinon.stub();

    loadDataSpy = sinon.spy(ComponentUnderTest.prototype, 'loadData');

    stubs.dispatch.returns(new Promise(function (resolve, reject) {
      resolve({});
    }));

    componentProperties = _.cloneDeep(mockComponentProperties);
    componentProperties.location = {
      query: {
        customerId: 11111
      }
    };

  });

  afterEach(function () {
    _.invokeMap(stubs, 'restore');
    loadDataSpy.restore();
    mockComponentProperties.dispatch.reset();
  });

  describe('in general', () => {

    beforeEach(function () {
      wrapper = shallow(<ComponentUnderTest {...componentProperties} />);
    });

    it('should render account activity Transactions component', function () {

      expect(wrapper.find('.activityTransactions').length).to.be.ok;

    });

  });
});

Any pointers in how to make that piece of info available for the test?

1
i think this is because you dont have this.props.customers.data thus your assignment with const customer = ... fails or no match found. you can add condition before dispatching actions - Rei Dien

1 Answers

0
votes

Where exactly is the object customer defined? If its global, just define it globally in your test:

global.customer = {};

Otherwise generally always pass data used in components via props. so when you use the component just pass it in:

<Component customerId={customer.id} />

Then testing is less painful.