OrangeSubmarine121
OrangeSubmarine121

Reputation: 182

Testing Style on React component

I have the following class with a function, that opens a modal (open_modal(...)) in a separate file to a component as I have a large number of modals that use this functionality.

import open from "open";
import $    from "jquery";

class ReactHelpers {

    static open_webpage(page_url) {
        open(page_url);
    }

    static open_modal(overlay_id, modal_id) {
        $(overlay_id).css("display", "block");
        $(modal_id).css("display", "block");
    }

    static close_modal(overlay_id, modal_id) {
        $(overlay_id).css("display", "none");
        $(modal_id).css("display", "none");
    }
}

export default ReactHelpers;



I am trying to assert that the open_modal function has added css to the divs in question as below:

    it('should close the modal', function () {
        const wrapper = shallow(
            <div id="overlay_id">
                <div id="modal_id">
                    <p>modal</p>
                </div>
            </div>
        )
        const overlay = wrapper.find('#overlay_id')
        const modal = wrapper.find('#modal_id')
        ReactHelpers.open_modal(overlay, modal);
        console.log('OVERLAY ', overlay);
        expect(overlay.prop('style')).toHaveProperty('display', 'block');
        expect(modal_style).toHaveProperty('display', 'block');
    });

Further, I'm sure to how the open_webpage function would be tested as this is a library function. In my other tests in my other components, I'm mocking this so it's never actually been tested.

Any help is greatly appreciated.

Thanks

Upvotes: 0

Views: 355

Answers (1)

yaya
yaya

Reputation: 8253

To test style of dom elements:

  1. You should mount the component (using mount), instead of just creating it (using shallow).

  2. Since you're changing the style of dom element directly, You should test the style of the dom element (component.getDOMNode().style.display), instead of testing the react style property (component.prop.style).

example:

import $ from "jquery";
it("should create a div and changes its color to red", () => {
  const wrap = mount(
      <div id="red_el"></div>
  );
  const el = wrap.find("#red_el").getDOMNode()
  $(el).css("color", "red");
  expect(el.style.color).toEqual("red");
});

In your case:

it("should open modal", () => {
  const wrapper = mount(
    <div>
      <div id="overlay" style={{ display: "none" }}>
        <div id="modal" style={{ display: "none" }}>
          overlay
        </div>
      </div>
    </div>
  );
  const overlay = wrapper.find("#overlay").getDOMNode();
  const modal = wrapper.find("#modal").getDOMNode();
  ReactHelpers.open_modal(overlay, modal);
  expect(overlay.style.display).toEqual("block");
  expect(modal.style.display).toEqual("block");
});

See it live on codesandbox (switch to the tests tab to run the tests .)

Upvotes: 1

Related Questions