我有以下自定义的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时进行的。
我已经尝试了作为艾默斯显示文档的第一个例子。但是,我认为这不适合我的用例,因为我想检查请求是否在我的服务中正确地形成。
我还尝试了以下代码,这些代码与预期的一样工作,但是我想测试我的服务(下面的代码不执行):
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()
})
})
})对如何纠正这个错误有什么想法吗?
发布于 2018-05-04 16:29:16
我知道这是一个老问题,但当我遇到同样的问题时,我会发布我的方法:
在本例中,您不需要使用sinon,因为您有一个axios实例,可以使用它来配置moxios (就像您已经做的那样)
beforeEach(() => {
moxios.install(http)
})
afterEach(() => {
moxios.uninstall(http)
})然后像这样测试您的方法:
it('test get', async () => {
const expectedPosts = ['Post1', 'Post2']
moxios.wait(() => {
const request = moxios.requests.mostRecent()
request.respondWith({ status: 200, response: expectedPosts }) //mocked response
})
const result = await fetchUserPosts(1)
console.log(result) // ['Post1','Post2']
expect(result).toEqual(expectedPosts)
})就这样。
问候
https://stackoverflow.com/questions/46179297
复制相似问题