Axios 连接不会让 Jest 终止

分享于2022年07月17日 axios jestjs node.js typescript 问答
【问题标题】:Axios 连接不会让 Jest 终止(Axios connection is not letting Jest gets terminated)
【发布时间】:2022-01-26 15:43:06
【问题描述】:

我是 Node/Jest 世界的新手。我正在尝试测试以下功能:

export async function visitPage(url: string) {
    const cookie =  ''
    let headers = {
    'authority': 'www.example.com',
    'pragma': 'no-cache',
    'cache-control': 'no-cache',
    'upgrade-insecure-requests': '1',
    'dnt': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'rtt': '350',
    'downlink': '1.45',
    'ect': '3g',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"macOS"',
    'referer': 'https://google.com',
    'accept-language': 'en-US,en;q=0.9,ur;q=0.8,zh-CN;q=0.7,zh;q=0.6',    
    'Accept-Encoding': 'gzip',
    'cookie': cookie,

    }

    try {
        const response = await axios({
            method: 'get',
            url: url,
            headers: headers
        });
        if (response.status == 200) {
            let html = response.data
            if(html.includes('Hello, Sign in')) {
                // console.log('Not logged in')
                return false
              }
        }
    } catch(error) {
        if (error.response) {
            console.log(error.response.data);   
        }
    }
    
    return true;
}

在测试中我正在做如下:

describe('Product', () => {
    it('visitPage', async () => {
        const pageData = await visitPage('https://example.com'); 
        // console.log(pageData)
        expect(pageData).toBe(false);
    });
});

测试通过但随后打印以下内容:

所有测试套件。

Jest has detected the following 1 open handle potentially keeping Jest from exiting:



●  TLSWRAP

      31 |
      32 |     try {
    > 33 |         const response = await axios({
         |                                     ^
      34 |             method: 'get',
      35 |             url: url,
      36 |             headers: headers


【解决方案1】:

您必须模拟 axios 实例的响应,以测试您的函数 How do I test axios in Jest? 的行为

但基本上,这就是你所需要的:

const axios = require("axios");
jest.mock("axios", () => Promise.resolve({ data: { foo: bar } }));

然后,每次您想要该承诺的另一个实现时,您只需这样做:

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

或:

axios.mockImplementation(() => Promise.reject('error))