gpt4 book ai didi

javascript - 使用 Moxios 模拟 Axios 调用以测试 API 调用

转载 作者:行者123 更新时间:2023-12-04 15:59:47 25 4
gpt4 key购买 nike

我有以下自定义 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 .

我尝试将 stubbing 作为 moxios 文档的第一个示例 shows .但是我认为这不适合我的用例,因为我想检查请求是否在我的服务中正确形成。

我也试过下面的代码,它按预期工作,但是我想测试我的服务(下面的代码 不做 ):
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()
})
})
})

关于如何修复错误的任何想法?

最佳答案

我知道这是一个老问题,但当我遇到同样的问题时,我将发布我的方法:

您不需要使用 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)
})

就是这样。

问候

关于javascript - 使用 Moxios 模拟 Axios 调用以测试 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46179297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com