Vue+jest Analog Asynchronous

1: first of all, I found a lot of web addresses by myself, but they didn"t work, and even the official website didn"t seem to work.

2: my question is how to simulate async

3: the project is built using vue-cli3 with its own test module

req.js encapsulates axios, and does some parameter processing before sending it

export default function req () {
    // ...
    axios.post()
}

table.vue calls the fetch method to get asynchronous data

<template>...</template>
<script>
import req from "@/utils/req"
export default {
    methods: {
        fetch () {
            // ...
            req(data).then(() => {
                // ...
            })
        }
    
    }
}
</script>
< H2 > Supplementary test code < / H2 >
jest.mock("@/utils/req")
// wrapper = mount(vue)
it("-sharp-sharp fetch data success", (done) => {
        wrapper.vm.fetch()
        wrapper.vm.$nextTick(() => {
          expect(wrapper.vm.cloneConfig).toEqual(mockData)
          done()
     })
 })

clipboard.png

table.vuefetchreqmock

clipboard.png

< H2 > reported this error. = 3 = I don"t understand. I use the table component of element. In my fetch function, req gets the data and binds it < / H2 >.

how can I use jest to test whether the fetch function is executed correctly and that req can return data

or how do I use jest to simulate the req function so that it doesn"t actually make a network request, but returns the simulation data I set

or there is a boss who can give a similar example, I will make a reference

Aug.29,2021

then you need mock axios


dear, have you solved this problem? I have the same problem.


I have also encountered this problem today. Although this post has been mentioned for a long time, I will answer it as a record. After trying, there are two ways to achieve it:

  1. the api file that mock needs to use,
  2. mock the entire ajax;.

the first way

// api/bank.ts
import axios from '@/assets/utils/axios';
import { AjaxData } from '@/store/types';
import { PREFIX } from './types';

// 
export interface BankItem {
  nameCode: string; // 
  name: string; // 
  icon: string; // logo url
  singleNumLimit: number; // :
  singleDayLimit: number; // :
}
export interface GetSupportBankListReturn {
  list: BankItem[];
}
export function getSupportBankList(showLoading = true) {
  return axios.get<AjaxData<GetSupportBankListReturn>>(
    `${PREFIX}/BankCardService/getSupportBankList`,
    {
      showLoading,
    },
  );
}
// BankLimitTable.vue
import { getSupportBankList } from '@/api/bank';

created() {
    getSupportBankList().then(({ data: resData }) => {
      const { code, data } = resData;

      if (!code && data && data.list) {
        this.banckLimitList = data.list;
      }
    });
  }
// bankLimitTable.test.ts
import { shallowMount } from '@vue/test-utils';
import BankLimitTable from './BankLimitTable.vue';
import flushPromises from 'flush-promises';
import * as Api from '@/api/bank';
jest.mock('@/api/bank'); // mock api

// mock
(Api.getSupportBankList as any).mockImplementation(() => {
  return Promise.resolve({
    data: {
      code: 0,
      data: {
        list: [
          {
            icon: 'icon',
            singleDayLimit: 1900000,
            name: '',
            nameCode: 'BCC',
            singleNumLimit: 15000000,
          },
          {
            icon: 'icon',
            singleDayLimit: '',
            name: '',
            nameCode: 'BCC',
            singleNumLimit: 15000000,
          },
        ],
      },
    },
  });
});

describe('', () => {
  test('', async () => {
    const wrapper = shallowMount(BankLimitTable);
    await flushPromises();
    expect(wrapper.vm.$data.banckLimitList.length).toBe(2);

    // 
    expect(
      wrapper.find('table  > tr:nth-child(2) > td:nth-child(3)').text(),
    ).toBe('1.9');

    expect(wrapper.html()).toMatchSnapshot();
  });
});

the second way
see the high-praise answer

in this post

Previous: How to use syscall in C language

Next: On the problem of introducing error report into Vue component

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ea9812-4f42f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ea9812-4f42f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?