How can I check the axioms for fun

I have this action in reaction

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

How do I check axios in this case? Jest has this use case on the site for asynchronous code, where they use a dummy function, but I don’t know if I can do this with axios? ref: https://facebook.imtqy.com/jest/docs/tutorial-async.html

I have done it so far to verify that it returns the correct type

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

I have no idea how to pass false data and verify that it is being returned, but does anyone have any ideas?

thanks in advance

+47
reactjs react-redux jestjs jest
source share
5 answers

I used axios-mock-adapter. In this case, the service is described in. / chatbot. In the mock adapter, you specify what needs to be returned when the API endpoint is consumed.

 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(); }); }); }); 

Here you can see the whole example:

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

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

+45
source share

Without using other libraries:

 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({ ... })); // ... }); 

You can specify a response code:

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

You can change the layout depending on the parameters:

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

Jest v23 introduced some syntactic sugar for mock promises:

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

can be simplified to

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

There is also the equivalent of declined promises: mockRejectedValue .

See Joke Docs Documents for more information. This GitHub discussion explains the scope of the jest.mock("axios") string jest.mock("axios") .

+40
source share

I could do this by following these steps:

  1. Create the __mocks __ / folder (as indicated by @Januartha's comment)
  2. axios.js file axios.js mock
  3. Use my implemented module when testing

The layout will happen automatically

Layout module example:

 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; }) }; 
+20
source share

I did this with nock , for example:

 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... }) }) 
+3
source share

For those who want to use axios-mock-adapter instead of the mockfetch example in redux documentation for asynchronous testing , I have successfully used the following

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); }); }); 

To check the successful case for signInUser in actions/index.js :

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

Given that this is a joke, calling localstorage should have been a mockery. This was in src/setupTests.js :

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

All Articles