DEV Community

Eulier Gonzalez
Eulier Gonzalez

Posted on

4 2

Vue-test-utils best practices for DOM finding & Events

When writing unit test, is helpful to imagine how the actual end user is gonna interact with our component and then we can design the test to replicate that behaviour.

How do we find DOM elements for testing our component?, here are some of the best practices from VueMastery when finding it.

Imagine that we use an Id or Class attribute to find a DOM element, but then down the road a designer or developer changes the id or the class of that element, so there’s a better, more future proof way to find elements.

A solution looks like this, for example with a button

In our component

<button data-test-id=name-button  ></button>
Enter fullscreen mode Exit fullscreen mode

Give our element a test specific, ID. Now in order to find that we’ll use this.

In our spec file

const button = wrapper.find([data-test-id=name-button])
Enter fullscreen mode Exit fullscreen mode

Setting things up this way helps us to decouple the test from the implementation details of that component.

Now we don’t need to worry about refactoring our test, just because a designer changes some class name around.
This is a recommended practice for production level tests.

Ok, but what about trigger events?. Again good practices from VueMastery, is by using this.

wrapper.trigger(submit)
Enter fullscreen mode Exit fullscreen mode

Writing in this way allow us to decouple the test from the implementation component’s detail. Again future-proofing our test.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️