我有以下自定义 Axios 实例:
import axios from 'axios'
export const BASE_URL = 'http://jsonplaceholder.typicode.com'
export default axios.create({
baseURL: BASE_URL
})
使用相应的服务:
import http from './http'
export async function fetchUserPosts(id) {
const reponse = await http.get(`/users/${id}/posts`)
return reponse.data
}
这是对所述服务的测试:
import moxios from 'moxios'
import sinon from 'sinon'
import http from '@/api/http'
import { fetchUserPosts } from '@/api/usersService'
describe('users service', () => {
beforeEach(() => {
moxios.install(http)
})
afterEach(() => {
moxios.uninstall(http)
})
it('fetches the posts of a given user', (done) => {
const id = 1
const expectedPosts = ['Post1', 'Post2']
moxios.stubRequest(`/users/${id}/posts`, {
status: 200,
response: expectedPosts
})
const onFulfilled = sinon.spy()
fetchUserPosts(1).then(onFulfilled)
moxios.wait(() => {
expect(onFulfilled.getCall(0).args[0].data).toBe(expectedPosts)
done()
})
})
})
使用 Karma + Jasmine 执行时会引发以下错误:
Uncaught TypeError: Cannot read property 'args' of null thrown
我想测试的是,当端点/users/{id}/posts
被击中时,会发回一个模拟响应。所有这一切都是在使用我的自定义 axios 实例时进行的http
。
我已经尝试将存根作为 moxios显示文档的第一个示例。但是我认为这不适合我的用例,因为我想检查请求在我的服务中是否正确形成。
我也尝试过使用以下代码,它按预期工作,但是我想测试我的服务(以下代码不这样做):
import axios from 'axios'
import moxios from 'moxios'
import sinon from 'sinon'
describe('users service', () => {
beforeEach(() => {
moxios.install()
})
afterEach(() => {
moxios.uninstall()
})
it('fetches the posts of a given user', (done) => {
const id = 1
const expectedPosts = ['Post1', 'Post2']
moxios.stubRequest(`/users/${id}/posts`, {
status: 200,
response: expectedPosts
})
const onFulfilled = sinon.spy()
axios.get(`/users/${id}/posts`).then(onFulfilled)
moxios.wait(() => {
expect(onFulfilled.getCall(0).args[0].data).toBe(expectedPosts)
done()
})
})
})
关于如何修复错误的任何想法?