This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

I’ll talk more about how to mock data.

The mock data

Why mock data? You can think of a few scenarios, such as if we want to test whether our request data actually calls Axios to send the request. Then the test efficiency is not too low, there is a big problem, so mock functions to simulate the request, not actually send the request.

Mock functions allow you to test links between code by erasing the actual implementation of functions, capturing calls to functions (and the parameters passed in those calls), capturing constructor instances when instantiated with new, and configuring return values when allowing testing.

Here’s an example:

export const fetchData = () => {
    return axios.get('/').then(res => res.data)
}

test('mock test fetchData', () => {
    return fetchData().then(data => {
        expect(eval(data)).toEqual('123')
    })
});
Copy the code

It is clear that our test case will not pass, connect, or request data. We can use mock data to test this.

import { Axios } from "axios";

jest.mock('axios')

test('mock test fetchData', () => {
    Axios.mockResolvedValue({
        data: "(function(){return '123'})()"
    })
    return fetchData().then(data => {
        expect(eval(data)).toEqual('123')
    })
});
Copy the code

Mock calls the jest. Mock function to tell Jest to use the mock instead of the real AXIos package when using axios next. Instead, we can override our fetchData function and call our fake fetchData function to simulate the test while the test executes. As follows:

// __mocks__/servers.js
export const fetchData = () => {
    return new Promise((resolve) => {
        resolve({
            data: "(function(){return '123'})()"
        })
    }).then(res => res.data)
}
Copy the code

Create a __mocks__ folder in the same directory as the test file, create the same file in that folder, override fetchData, and mock. Test.js as follows:

// Tell jest to look for mock jest ('./ Servers.js ') import {fetchData} from "./servers"; test('mock test fetchData', () => { return fetchData().then(data => { expect(eval(data)).toEqual('123') }) });Copy the code

Both methods implement the mock data of the data request to complete the test. Is there another scene? For example, the servers.js file has not only fetchData (request required), but also getNumber (no request required), we can just mockfetchData, if we want to do that, Add getNumber to __mocks__/ Servers.js, but he doesn’t want it. What do we do? Below, we import separately, using the jest.requireActual() function to import the real function without mocking.

jest.mock('./servers.js')

import { fetchData } from "./servers";
const { getNumber } = jest.requireActual('./servers')

test('mock test fetchData', () => {
    return fetchData().then(data => {
        expect(eval(data)).toEqual('123')
    })
});

test('test getNumber', () => {
    expect(getNumber()).toBe(123)
})
Copy the code

The mock function properties are described below, more on the official API.

Some of the properties of the mock function can be seen by printing mockCallback. Mock.

function forEach(items, callback) { for (let index = 0; index < items.length; index++) { callback(items[index]); } } test('mock jest.fn', () => { const mockCallback = jest.fn(x => 42 + x); forEach([0, 1], mockCallback); / / The mock The function is called twice / / number of mock function is called expect (mockCallback. Mock. Calls. Length), place (2); // The first argument of The first call to The function was 0 expect(mockCallback.mock.calls[0][0]).toBe(0); // The first argument of the second call to the function was 1 expect(mockCallback.mock.calls[1][0]).toBe(1); // The return value of The first call to The function was 42 expect(mockCallback.mock.results[0].value).toBe(42); })Copy the code