Home > Net >  jest.spyOn component property
jest.spyOn component property

Time:03-30

Can jest.spyOn component property? I need to make sure isLoading is always true

export default {  
  data() {
    return {     
      isLoading: false,
    };
  },
  methods: {
    async loadData() {
      this.isLoading = true;
    }
  }
}

CodePudding user response:

You can't spy on a data property, but you don't really need to in this case.

Instead, you could stub out loadData(), and mount the component with the initial value for isLoading:

  1. Set MyComponent.methods.loadData to jest.fn() to stub it out.

  2. Mount the component with an initial data() property, returning true for the isLoading property.

import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'

describe('MyComponent', () => {
  it('sets isLoading', () => {
    1️⃣
    MyComponent.methods.loadData = jest.fn()

    const wrapper = shallowMount(MyComponent, {
      2️⃣
      data() {
        return {
          isLoading: true,
        }
      },
    })

    expect(wrapper.vm.isLoading).toBe(true)
    expect(wrapper.text()).toContain('Loading...')
  })
})

demo

  • Related