how to select element text with react+enzyme

前端 未结 4 1057
不知归路
不知归路 2021-02-02 07:13

Just what it says. Some example code:

let wrapper = shallow(
); const b = wrapper
相关标签:
4条回答
  • 2021-02-02 07:48

    I ran into this post when searching for ways to select all/some of the text within a textarea within jest and enzyme. For those who are looking for the same thing, you do can the following to select some text (provided you already know the length):

    let wrapper;
    let textareaNode;
    beforeEach(() => {
        wrapper = mount(<Textarea value="Hello world" />);
        textareaNode = () => wrapper.find("textarea").getDOMNode();
    });
    
    it("selects all of the select within the given range", () => {
        textareaNode().setSelectionRange(0, 6);
        wrapper.find("button").simulate("click"); // this would delete the selection via a ref
        expect(wrapper.find("textarea").props().value).toEqual("world");
    });
    
    0 讨论(0)
  • 2021-02-02 07:53

    Don't forget that you are passing a node (ReactElement) to shallow function, and there is no HTML attribute class in React. You have to use className.

    From React documentation

    All attributes are camel-cased and the attributes class and for are className and htmlFor, respectively, to match the DOM API specification.

    This test should works

    const wrapper = shallow(<div><button className='btn btn-primary'>OK</button></div>);
    const button = wrapper.find('.btn'); 
    expect(button.text()).to.be.eql('OK');
    
    0 讨论(0)
  • 2021-02-02 07:59

    I think @louis-barranqueiro has probably answered your underlying question. That is, you want a CSS selector and so you should have been using className not class.

    However, to try and answer the question of how to select an element's text using the actual example you gave:

    let wrapper = shallow(<div><button class='btn btn-primary'>OK</button></div>);

    you'd need to use something like an object property selector, e.g.:

    expect(wrapper.find({ class: "btn btn-primary" }).text()).to.equal('OK');

    or prop syntax:

    expect(wrapper.find('[class="btn btn-primary"]').text()).to.equal('OK');

    (or even more explicitly):

    expect(wrapper.find('button[class="btn btn-primary"]').text()).to.equal('OK');

    0 讨论(0)
  • 2021-02-02 08:03

    If you found this while looking for "includes text", try:

    it('should show correct text', () => {
      const wrapper = shallow(<MyComponent />);
      expect(wrapper.text().includes('my text')).toBe(true);
    });
    
    0 讨论(0)
提交回复
热议问题