Skip to content

Improving find and findAll API for asserting presence of stubs  #651

Closed
@lmiller1990

Description

@lmiller1990

What problem does this feature solve?

If I want to assert a stub was rendered, I have to do the following:

Demo component:

<!-- component.vue -->
<template>
  <div>
    <Hello />
  </div>
</div>

I want to assert Hello is rendered one time.

// test
const HelloStub = {
  'name': "Hello"
  render: h => h('div')
}

const wrapper = shallow(Component}

expect(wrapper.find(HelloStub).exists()).toBe(true)

I always need to create a minimal:

const HelloStub = { name: "Hello", render: h => h("div") }

That is an extra (correctly formatted) four lines - over half the test.

My current workflow simply defines a helper:

const createStub = name => ({ name, render: h => h("div") })

Which adds an extra line for the import, and another for create the stub in every test. 1/3 of the test is, in my opinion, unnecessary boilerplate setup.

What does the proposed API look like?

I find myself defining and importing the above helper function in every project, and importing it to many tests. One idea would be to add this method to vue-test-utils. This goes against one design goal, "keeping the API surface small and straightforward". However, it supports one other goal, "The problem should also be common enough to justify the addition". I think asserting components are rendered is done is many tests.

I had two proposed APIs:

  1. include helper in vue-test-utils
import { shallowMount, createStub } from "@vue/test-utils" 

const Hello = createStub("Hello")
const wrapper = shallowMount(Component)

expect(Component.find(Hello).exists()).toBe(true)
  1. passing a string to find, and findAll checks for stubs
import { shallowMount } from "@vue/test-utils" 

const wrapper = shallowMount(Component)

expect(Component.find("Hello").exists()).toBe(true)

Since Vue components cannot clash with existing HTML elements, it is easy to know when find receives a HTML element like <div>, and when it's looking for an actual component. In the case of an a actual component, find should look for stubs instead of html elements.

I like the second solution more because it leads to more compact code, and doesn't change overall API very much.

I am happy to implement either.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions