Summary of RepositoryFactory Implementation
An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here
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()
}
Currently working on writing test code for the above files and need guidance on how to proceed with it.
My Attempt at Writing Test Code
Some initial test code was written but encountered an error related to this
.$axios displaying '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) <- encountering error here
})
)}