【问题标题】:How to write test for RepositoryFactory in Vue.js/Nuxt.js如何在 Vue.js/Nuxt.js 中为 RepositoryFactory 编写测试
【发布时间】:2022-01-21 06:03:34
【问题描述】:

夏天

我已经为 Vue.js/Nuxt.js 应用程序中的 API 连接实现了 RepositoryFactory 模式。
https://medium.com/canariasjs/vue-api-calls-in-a-smart-way-8d521812c322

hogeRepository.ts

import { NuxtAxiosInstance } from '@nuxtjs/axios'

type queryData = {
  q: string | null
}

export const HogeRepository = ($axios: NuxtAxiosInstance) => ({
  createResource (apiVersion: Number) {
    return `v${apiVersion}/meetings`
  },

  get (data: queryData, version = 1) {
    const url = `${this.createResource(version)}`
    return $axios.get(url, {
      params: { ...data }
    })
  },
})

repository.ts

import { HogeRepository } from '~/api/hogeRepository'

export interface Repositories {
  hoge: typeof HogeRepository
}

const repositories = {
  hoge: HogeRepository
}

export const RepositoryFactory = {
  get: (key : keyof Repositories) => repositories[key]
}

hoge.vue

async test () {
  await RepositoryFactory.get('hoge')(this.$axios).get()
}

现在我正在尝试为这些文件编写测试代码。
我想知道如何为他们编写测试代码。

我尝试过的

我试着写一些测试代码。
但它在this.$axios 上显示错误Object is possibly 'undefined'.ts(2532)

repositoryFactory.spec.ts

import { RepositoryFactory } from '~/api/repositoryFactory'

describe('RepositoryFactory', () => {
  it('Should create repositories', () => {
    const repositoryFactory = RepositoryFactory.get('hoge')(this.$axios) <- error on this
  })
)}

【问题讨论】:

    标签: typescript vue.js jestjs nuxt.js


    【解决方案1】:

    你必须模拟 $axios 来测试它。检查这个link

    jest.mock('axios', () => ({
      get: Promise.resolve('value')
    }))
    
    

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2020-12-22
      相关资源
      最近更新 更多