Метод модульного тестирования с jQuery и this.random () внутри, в vue - PullRequest
0 голосов
/ 29 апреля 2020

Я новичок в модульном тестировании, я хочу протестировать компонент с методом, который внутри этого метода я использую this.random функцию и jQuery с Jest.

Я хочу проверить, если openPost метод вызывается или нет?

Когда я получаю тест, он выдает ошибки this.$ is not a function и this.random is not a function.

Как мне написать тест?

Компонент:

<template>
    <div @click="openPost('note')" class="ml-3 text-center pointer noteBtn">
      <i class="fal color-9e fa-handshake"></i>
      <div class=" fs-14 color-50">metting</div>
    </div>
</template>

export default {
  data() {
    return {
      addNewKey: '',
      addNewType: '',
      showModal: false,
      showNegoModal: false,
      data: {}
    }
  },
  methods: {
    openPost(type, data) {
      this.addNewType = type
      if (data) this.data = data
      else this.data = {}
      this.addNewKey = this.random()
      this.$nextTick(() => {
        if (type === 'call') {
          this.$('#createContact').modal('show')
        } else if (type === 'note') {
          this.$('#createNote').modal('show')
        } else if (type === 'negotiation') {
          if (data) {
            this.showNegoModal = true
            this.$nextTick(() => {
              this.$('#CompanyNegoModal2').modal('show')
            })
          } else this.createnegopopup.show = true
        }
      })
    }
}

Тест:

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

global.Math.random = jest.fn()
global.$ = jest.fn()

describe('AddDetailToCompany', () => {
  let wrapper = null
  beforeEach(() => {
    wrapper = shallowMount(component)
  })
  afterEach(() => {
    wrapper.destroy()
    jest.clearAllMocks()
  })
  test('calls openPost when noteBtn is clicked', () => {
    const openPost = jest.fn()
    wrapper.find('.noteBtn').trigger('click')
    expect(openPost).toHaveBeenCalledWith('note')
    wrapper.vm.$nextTick().then(function() {
      expect(global.Math.random).toHaveBeenCalled()
      expect(global.$).toHaveBeenCalledWith('#createNote')
    })
  })
})

1 Ответ

0 голосов
/ 30 апреля 2020

Протестированный компонент не имеет доступа к глобальному $, но свойство экземпляра, которое необходимо смоделировать:

wrapper = shallowMount(component, { mocks: { $ } })

Для того, чтобы jQuery было цепным, требуется предоставить цепные макеты:

modal = jest.fn();
$ = jest.fn().mockReturnValue({ modal });
...