Components with props

Tram Ho

Set props with propsData

propsData can be used with both mount and shallowMount . It is often used to check components that receive props from its parent component.

propsData is passed the second argument of either shallowMount or mount as follows:

Create a component model

Creating a simple <SubmitButton> component has two props : msg and isAdmin . Depending on the value of isAdmin , this component will contain a <span> in two states:

  • Not Authorized if isAdmin is false (or not adopted as a prop)
  • Admin Privileges if isAdmin is true

Create the first test

We will make a confirmation about the notification in case the user does not have admin rights.

Run the test with yarn test:unit . The results we get:

The results of console.log(wrapper.html()) also printed:

We can see that the msg prop is processed and the markup is exactly what is displayed.

Create the second experiment

We will check the status when isAdmin is true :

Run the test with yarn test:unit and test the results:

We also have markup with console.log(wrapper.html()) :

It can be seen that prop isAdmin is used to render the <span> element correctly.

Refactoring the tests again

We will refactor tests that comply with “Don’t Repeat Yourself” (DRY). Since all tests pass, we can be confident to refactor them again. As long as all tests are still passable after refactor, make sure not to break anything.

Refactor with Factory Function

In both tests, we call shallowMount and then use the propsData object repeatedly. We can refactor it again by using a factory function. A factory function is a function that returns an object – it creates objects, hence the name “factory” function.

Above is a function that will shallowMount a SubmitButton component. We can pass any props to change the first factory argument. DRY the tests with the factory function.

Run the test again. Everything to pass easily.

Conclude

  • By using propData passes when mounting a component, you can set the props used in the test.
  • Factory functions can be used to DRY your tests
  • Instead of using propsData , we can also use setProps to set props values ​​during testing.

Reference

Translated from: https://lmiller1990.github.io/vue-testing-handbook/components-with-props.html#setting-props-with-propsdata

Share the news now

Source : Viblo