gpt4 book ai didi

javascript - axios-mock-adapter 与预期的 url 不匹配

转载 作者:太空宇宙 更新时间:2023-11-04 01:35:55 24 4
gpt4 key购买 nike

我曾经使用 axios-mock-adapter 取得了巨大成功,但最近几次我尝试使用它,我的路线似乎从未匹配,并且它仍在尝试执行真正的端点。

为什么此单元测试仍然调用 example.com 并返回 404?我原以为它会返回 500。

测试/libs/orgService/index.spec.js

const uuid = require('uuidv4')
const axios = require('axios')
const MockAdapter = require('axios-mock-adapter')
const mock = new MockAdapter(axios)
const { getOrgById } = require('../../../src/libs/orgService/index')
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
const expect = chai.expect
const orgServiceHost = 'https://example.com'

describe.only('#getOrgById failure', () => {
const id = uuid()
before(() => {
console.log('`${orgServiceHost}/organizations/${id}` = ', `${orgServiceHost}/organizations/${id}`)
mock.onGet(`${orgServiceHost}/organizations/${id}`).reply(500) <-- SHOULD BE RETURNING 500!!
})

after(() => {
mock.reset()
})

it('should fail to fetch an organization', () => {
return expect(getOrgById(orgServiceHost, id, tkn)).to.eventually.be.rejected
})
})

src/libs/orgService/index.js

const axios = require('axios')

function getOrgById (orgServiceHost, id, token) {
log.debug('orgServiceHost = ', orgServiceHost)
log.debug('id = ', id)
log.debug('token = ', token)
return new Promise((resolve, reject) => {
if (id === undefined) {
return resolve()
}
console.log('`${orgServiceHost}/organizations/${id}` = ', `${orgServiceHost}/organizations/${id}`)
axios({
url: `${orgServiceHost}/organizations/${id}`,
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json',
}
})
.then(res => {
return resolve(res.data)
})
.catch(err => {
log.error('getOrgById err = ', err)
return reject(err)
})
})
}

module.exports = { getOrgById }

最佳答案

(注意:我没有足够的信用来发表评论,因此将以下内容发布为答案。)

我不确定这是否有效,但请尝试创建一个 axios 实例

before(() => {
instance = AxiosApi.getAxiosInstance();
mock = new MockAdapter(instance);
mock.onGet(`${orgServiceHost}/organizations/${id}`).reply(500);
})

关于javascript - axios-mock-adapter 与预期的 url 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54638466/

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