首页 > 解决方案 > 用玩笑模拟 axios 和 kitsu

问题描述

我正在创建一些测试,并使用 Kitsu ( https://github.com/wopian/kitsu/tree/master/packages/kitsu ) 作为使用 API 的客户。

我需要模拟 API 请求,但我不能。Kitsu 内部使用 axios,不知道如何模拟结构:

Kitsu {
  camel: [Function: index],
  resCase: [Function: index$1],
  plural: [Function: pluralize] {
    plural: [Function],
    isPlural: [Function],
    singular: [Function],
    isSingular: [Function],
    addPluralRule: [Function],
    addSingularRule: [Function],
    addUncountableRule: [Function],
    addIrregularRule: [Function]
  },
  headers: {
    Accept: 'application/vnd.api+json',
    'Content-Type': 'application/vnd.api+json'
  },
  axios: [Function: wrap] {
    request: [Function: wrap],
    getUri: [Function: wrap],
    delete: [Function: wrap],
    get: [Function: wrap],

我需要在 axios 属性中模拟 get 方法。我怎么能用 jest 做到这一点?谢谢

标签: javascriptjestjs

解决方案


您可以使用axios-mock-adapterhttps://www.npmjs.com/package/axios-mock-adapter

例如

const axios = require('axios');
const MockAdapter = require('axios-mock-adapter');
const mock = new MockAdapter(axios);

mock.onGet('http://somehost/path').reply(200, 'response goes here');

推荐阅读