8

How do I retrieve the button text from a found element in vue-test-utils? I am using v1.0.0-beta.10

For example, in my vue file I have a button like:

el-button(@click.native="cancel",
          size="small",
          native-type="button") Cancel

Then in my tests:

const button = wrapper.findAll({
  name: "el-button"
})

console.log('buttonAll is', button.at(2).vnode.$attrs) // {}

I get an empty object. Even better, how can I directly query that Vue component based on button text?

2 Answers 2

9

You can retrieve the button text from a found element like this:

 describe('Button', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(VueComponent);
  });
  it('has a button with text mazino', () => {
    let button = wrapper.find('.mazino');
    expect(button.text()).toBe('mazino');
  });
});
9
  • 3
    Isn't that just a class selector? I get an error where button equals ErrorWrapper { selector: '.Cancel' } Commented Jan 18, 2018 at 2:21
  • 3
    I don't have an error thrown, but I am unable to find a button that I can use. You can see above I reference that it is an ErrorWrapper, so I can't do anything with it. Ideally I'd like to trigger a click event. Commented Jan 18, 2018 at 17:37
  • 1
    If I call text() on it I will get this error: Error: [vue-test-utils]: cannot call wrapper.text() on a wrapper without an element Commented Jan 18, 2018 at 18:58
  • 1
    @writofmandamus that means that find was unsuccessful. The selector you're using can't be found in the render tree.
    – Edward
    Commented Jan 28, 2018 at 10:40
  • 1
    let button = wrapper.findAll('.mazino'); Works for me Commented May 11, 2021 at 8:04
5

This is how I query buttons by text

function findByText (wrap, selector, text) {
  return wrap.findAll(selector).filter(n => n.text().match(text));
}

describe('Button', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(VueComponent);
  });
  it('has a button with text foo', () => {
    const button = findByText(wrapper, 'button', /foo/).at(0);
    expect(button.exists()).toBeTruthy();
  });
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.