首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >axios-mock-适配器与预期的url不匹配

axios-mock-适配器与预期的url不匹配
EN

Stack Overflow用户
提问于 2019-02-12 04:18:01
回答 2查看 2.6K关注 0票数 1

我曾经非常成功地使用axios-mock-adapter,但最近几次我尝试使用它时,我的路由似乎从未匹配过,它仍在尝试执行一个真正的端点。

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

test/libs/orgService/index.spec.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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 }
EN

回答 2

Stack Overflow用户

发布于 2019-02-21 02:01:20

(注:我没有足够的信用来评论,所以请将下面的答案发布为答案。)

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

代码语言:javascript
复制
before(() => {
 instance = AxiosApi.getAxiosInstance();
 mock = new MockAdapter(instance);
 mock.onGet(`${orgServiceHost}/organizations/${id}`).reply(500);
})
票数 1
EN

Stack Overflow用户

发布于 2019-02-21 03:24:09

问题是您从服务返回一个Promise。尝试如下所示:

代码语言:javascript
复制
it('should fail to fetch an organization', (done) => {
    getOrgById(orgServiceHost, id, tkn)
      .then(() => {
        assert.fail("custom error message"); // or any other failure here
        done();
      }).catch((exception) => {
        expect(true).toBeTruthy(); // or any other way to pass the test
        done();
      });
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54638466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档