admin管理员组

文章数量:1287629

I have the following react-native test code.

it('should render a <BorderlessButton />', () => {
    expect(wrapper.find(BorderlessButton)).toHaveLength(1);
    expect(wrapper.find(BorderlessButton).props.text.toEqual('D'));
  });

This doesn't work properly. What I want to do is to check the button text. How can I do this?

I have the following react-native test code.

it('should render a <BorderlessButton />', () => {
    expect(wrapper.find(BorderlessButton)).toHaveLength(1);
    expect(wrapper.find(BorderlessButton).props.text.toEqual('D'));
  });

This doesn't work properly. What I want to do is to check the button text. How can I do this?

Share Improve this question edited Aug 19, 2019 at 9:35 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Aug 19, 2019 at 9:19 Shashika VirajhShashika Virajh 9,47720 gold badges64 silver badges112 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 9

I think we need to replace .props with .props(), also the syntax for toEqual should be like this -:

expect(wrapper.find(BorderlessButton).props().text).toEqual('D');

In my case, it worked with the following syntax

expect(wrapper.find(BorderlessButton).text()).toEqual('D');
describe("Test Button ponent", () => {
  let container = null;
  let clickFn = null;
  beforeEach(() => {
    clickFn = jest.fn();
    container = shallow(<Button buttonAction={clickFn} value="send" />);
  });
  it("button value", () => {
    
    expect(container.find("button").props().value).toEqual("send");
  });
});

According to Jest Quickstart documentation:

test('loads and displays greeting', async () => {
  render(<Fetch url="/greeting" />)

  expect(screen.getByRole('heading')).toHaveTextContent('hello there')
  expect(screen.getByRole('button')).toBeDisabled()
})

It looks like the toHaveTextContent method should work for you.
Personally, I don't use getByRole on projects, but usually getByTestId.
It looks like this:

expect(screen.getByTestId('button-test-id')).toHaveTextContent('value')

本文标签: javascriptCheck button text in jest and enzymeStack Overflow