1

Hi I am new to Jest and Java Script. I want to perform a test over one of my components.

I want to check that the Admin see the sentence:

"Please select a user to show his/her donations:"

My suggestion was something like:

const sentence = "Please select a user to show his/her donations:"
it('Shows: Please select a user to show his/her donations:', () => {
  const admin = shallow(<AdminViewComponent />);
  const wantedSentence = admin.find(sentence);
  expect(wantedSentence).toEqual(true);
});

But as this does not work I would like to get another suggestions.

Here is the component that I want to test:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Typeahead } from 'react-bootstrap-typeahead'; // ES2015
import axios from 'axios';
import { WholeScreen } from './WholeScreenComponent.js';

export class AdminViewComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      emailList: [],
      selectedUser: "",
      SelectedUserDonationData: {}
    };

    this._handleChange = this._handleChange.bind(this);
  }

  getInitialState() {
    return {
      // [{}] is weird, either use undefined (or [] but undefined is better).
      // If you use [], you loose the information of a "pending" request, as 
      // you won't be able to make a distinction between a pending request, 
      // and a response that returns an empty array
      emailList: undefined,
      selectedUser: undefined,
      SelectedUserDonationData: undefined
    }
  }
  componentDidMount() {
    this.setState({ emailList: undefined });
    return axios.get('./api/user/', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.props.token
      }
    }).then(response => {
      const emailListResult = response.data;
      this.setState({ emailList: emailListResult });

    }).catch(function (error) {
      console.log(error);
    });
  }

  _handleChange(SelectedUser) {
    this.setState({ selectedUser: SelectedUser, selectedUserDonationData: undefined });


    axios.get('./api/user/' + SelectedUser + '/',
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.props.token
        }
      }).then(response => {
        const selectedUserDonationDataResponse = response.data;
        this.setState({ selectedUserDonationData: selectedUserDonationDataResponse });
        console.log(selectedUserDonationDataResponse);

      }).catch(function (error) {
        console.log(error);
      });

  }

  render() {
    var adminView;
    if (!this.state.emailList) {
      adminView = <div>Please wait while we retrieve all users...</div>
    }
    else {
      adminView = (
        <div>
          <div>
            Please select user to show his/her donations
          </div>
          <Typeahead
            placeholder="Select user email..."
            onChange={this._handleChange}
            options={this.state.emailList} />
        </div>
      );
    }

    var selectedUserData;
    if (this.state.selectedUserDonationData) {
      selectedUserData = (
        <div className="AdminViewData">
          <h4 className="DtatOf">
            Showing donations of: {this.state.selectedUser}
          </h4>
          <WholeScreen data={this.state.selectedUserDonationData.DonationsList} />
        </div>
      );
    }

    var url = "./api/user/";
    return (
      <div className="AdminView">
        {adminView}
        {selectedUserData}
      </div>
    );
  }
}

The line that I want to test is inside the render() function

adminView = <div>Please wait while we retrieve all users...</div>
6

2 Answers 2

1

Since you do not have a class or id on your div element it should be difficult to retrieve it using .find(). Luckily you could also use .containsMatchingElement(node) to check whether your Component contains an element, instead of a selector. In other words you can do the following:

  const elementToCheck = "<div> Please select user to show his/her donations </div>"
  it('Shows: Please select a user to show his/her donations:', () => {
    const admin = shallow(<AdminViewComponent />);
   expect(admin.containsMatchingElement(elementToCheck)).toEqual(true);
  });

read more about .containsMatchingElement here.

Sign up to request clarification or add additional context in comments.

Comments

1

It is easier if you add a selectable attribute to the DOM node.

  it('Shows: Please select a user to show his/her donations:', () => {
    const admin = mount(<AdminViewComponent />);
    const actualText = admin.find("[data-id='someSelector']").text();
    const expectedText = "Please select a user to show his/her donations";

    expect(actualText).toEqual(expectedText);
  });

  /*
     Alternately you could use a snapshot test as this would remove 
     the need to copy the text into the test
  */


  it('Shows: Please select a user to show his/her donations:', () => {
    const admin = mount(<AdminViewComponent />);
    const actualText = admin.find("[data-id='someSelector']").text();

    expect(actualText).toMatchSnapshot();
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.