我如何在 Jest 中测试 axios?

How do I test axios in Jest?

我在 React 中有这个动作:

export function fetchPosts() {
    const request = axios.get(`${WORDPRESS_URL}`);
    return {
        type: FETCH_POSTS,
        payload: request
    }
}

在这种情况下如何测试 Axios

Jest 在他们的网站上有这个使用模拟函数的异步代码的用例,但是我可以用 Axios 做到这一点吗?

参考:An Async Example

到目前为止我这样做是为了测试它是否返回正确的类型:

it('should dispatch actions with the correct type', () => {
    store.dispatch(fetchPosts());
    let action = store.getActions();
    expect(action[0].type).toBe(FETCH_POSTS);
});

如何传入模拟数据并对其进行测试returns?

我用了axios-mock-adapter。 在这种情况下,该服务在 ./chatbot 中进行了描述。 在模拟适配器中,您指定在使用 API 端点时要 return 的内容。

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';

describe('Chatbot', () => {
    it('returns data when sendMessage is called', done => {
        var mock = new MockAdapter(axios);
        const data = { response: true };
        mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);

        chatbot.sendMessage(0, 'any').then(response => {
            expect(response).toEqual(data);
            done();
        });
    });
});

你可以在这里看到整个例子:

服务: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

测试: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

我用 nock 完成了这个,像这样:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

我可以按照以下步骤进行操作:

  1. 创建一个文件夹__mocks__/(正如@Januartha 评论所指出的)
  2. 实施 axios.js 模拟文件
  3. test
  4. 上使用我实现的模块

模拟将自动发生

模拟模块示例:

module.exports = {
    get: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
    }),
    post: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
        if (url === '/something2') {
            return Promise.resolve({
                data: 'data2'
            });
        }
    }),
    create: jest.fn(function () {
        return this;
    })
};

对于那些希望使用 axios-mock-adapter 代替 Redux documentation for async testing 中的 mockfetch 示例的人,我成功地使用了以下内容:

文件actions.test.js:

describe('SignInUser', () => {
  var history = {
    push: function(str) {
        expect(str).toEqual('/feed');
    }
  }

  it('Dispatches authorization', () => {
    let mock = new MockAdapter(axios);
    mock.onPost(`${ROOT_URL}/auth/signin`, {
        email: 'test@test.com',
        password: 'test'
    }).reply(200, {token: 'testToken' });

    const expectedActions = [ { type: types.AUTH_USER } ];
    const store = mockStore({ auth: [] });

    return store.dispatch(actions.signInUser({
        email: 'test@test.com',
        password: 'test',
      }, history)).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
  });

});

为了在文件actions/index.js中测试signInUser的成功案例:

export const signInUser = ({ email, password }, history) => async dispatch => {
  const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
    .catch(({ response: { data } }) => {
        ...
  });

  if (res) {
    dispatch({ type: AUTH_USER });                 // Test verified this
    localStorage.setItem('token', res.data.token); // Test mocked this
    history.push('/feed');                         // Test mocked this
  }
}

鉴于这是开玩笑的,因此必须模拟 localstorage 调用。这是在文件 src/setupTests.js:

const localStorageMock = {
  removeItem: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

不使用任何其他库:

import * as axios from "axios";

// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");

// ...

test("good response", () => {
  axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
  // ...
});

test("bad response", () => {
  axios.get.mockImplementation(() => Promise.reject({ ... }));
  // ...
});

可以指定响应代码:

axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));

可以根据参数更改模拟:

axios.get.mockImplementation((url) => {
    if (url === 'www.example.com') {
        return Promise.resolve({ data: {...} });
    } else {
        //...
    }
});

Jest v23 引入了一些用于模拟 Promises 的语法糖:

axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));

可以简化为

axios.get.mockResolvedValue({ data: {...} });

对于被拒绝的承诺,还有一个等价物:mockRejectedValue

进一步阅读:

看看这个

  1. 要测试的函数album.js
const fetchAlbum = function () {
 return axios
   .get("https://jsonplaceholder.typicode.com/albums/2")
   .then((response) => {
     return response.data;
   });
};
  1. 测试album.test.js
const axios = require("axios");
const { fetchAlbum } = require("../utils.js");

jest.mock("axios");

test("mock axios get function", async () => {
    expect.assertions(1);
    const album = {
      userId: 1,
      id: 2,
      title: "sunt qui excepturi placeat culpa",
    };
    const payload = { data: album };
    // Now mock axios get method
    axios.get = jest.fn().mockResolvedValue(payload);
    await expect(fetchAlbum()).resolves.toEqual(album);
  });