簡體   English   中英

在 Vue 中使用 Jest Mock 測試導出的模塊

[英]Test exported module with Jest Mock in Vue

我正在嘗試對導出的模塊進行模擬,但我不知道該怎么做。 以下是我的代碼。

應用程序接口

// @/src/api/index.js

...
export const foo = {
  fetch() {
    return Promise.resolve()
  }
}

視圖

import { foo } from '@/api' 

...
data() {
  return {
    receivedData: ''
  }
},
methods: {
  onClickButton() {
    // event listener
    foo.then(data => { this.receivedData = data }
  }
}

測試規范.js

import { shallowMount } from '@vue/test-utils'
import { foo } from '@/api'
...
jest.mock('../../../src/api/index.js') // it does not mock foo

...
  beforeEach(() => {
    foo.mockClear()
    // error : _api.foo.mockClear is not a function
  })

在此示例中,我如何為以名稱導出foo進行模擬,而不是像exported default foo那樣默認導出的模塊。

應用程序接口

// @/src/api/index.js

...
export const foo = {
  fetch() {
    return Promise.resolve()
  }
}

// add following
export default {
  foo
}

測試規范.js

import { shallowMount } from '@vue/test-utils'
import api from '@/api' // get a object which have all api functions
...
jest.mock('../../../src/api/index.js', () => {
  // make it similar with 'export default' of api/index.js
  return {
    foo: {
      fetch: jest.fn(() => {
        return {
          then(callback) {
            // pass dummy data as you want or need
            callback({ data: { success: true } })
          }
        }
      })
    }
  }
})

...
  beforeEach(() => {
    // clear mock of each mocked function
    api.foo.fetch.mockClear()
  })

  it('test api', () => {
    const wrapper = shallowMount(Component)
    wrapper.find('button').trigger('click')

    expect(api.foo.fetch).toHaveBeenCalled() // pass it
  })

  it('test api2', () => {
    expect(api.foo.fetch).toHaveBeenCalled() // do not pass it
  })

這樣,我可以處理模擬函數並檢查更改的 ui 元素或 vue 實例的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM