axios-mock-adapter与预期的网址不匹配

时间:2019-02-11 20:18:01

标签: javascript node.js axios axios-mock-adapter

我曾经很成功地使用axios-mock-adapter,但是最近几次尝试使用它,我的路由似乎从未匹配,并且仍在尝试执行真正的端点。

为什么此单元测试仍要调用example.com并返回404?我本来希望它能返回500。

test / 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 }

2 个答案:

答案 0 :(得分:0)

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

我不确定是否可以,但是请尝试创建axios实例

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

答案 1 :(得分:0)

问题是您从服务返回了Promise。尝试类似的东西:

it('should fail to fetch an organization', () => {
    getOrgById(orgServiceHost, id, tkn)
      .then(() => {
        assert.fail("custom error message"); // or any other failure here
      }).catch((exception) => {
        expect(true).toBeTruthy(); // or any other way to pass the test
      });
  });