开玩笑-如何模拟模块使用的类? [英] Jest - how to mock a Class used by a module?

查看:59
本文介绍了开玩笑-如何模拟模块使用的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课:

class RequestTimeout {
    constructor(timeoutMilliseconds) {
        this.timeoutMilliseconds = timeoutMilliseconds;
        this.timeoutID = undefined;
    }

    start() {
        return new Promise((resolve, reject) => {
            this.timeoutID = setTimeout(() => reject(new Error(`Request attempt exceeded timeout of ${this.timeoutMilliseconds}`)), this.timeoutMilliseconds);
        });
    }

    clear() {
        if (this.timeoutID) clearTimeout(this.timeoutID);
    }
}

module.exports = RequestTimeout;

此类在模块中使用:

const RequestTimeout = require('./request-timeout');

function Request() {
  ...

  async function withTimeout(request, ms) {
        const timeout = new RequestTimeout(ms);

        return Promise.race([
            request(),
            timeout.start(),
        ])
            .then(
                response => {
                    timeout.clear();
                    return response;
                },
                err => {
                    timeout.clear();
                    throw err;
                }
            );
    }

  ...
}

如何在使用Request的测试中模拟RequestTimeout?例如:

How do i mock RequestTimeout in a test using Request? For example:

it('should clear the timeout following a successful response', async () => {
  nock('http://example.com')
    .get('/')
    .reply(200, { example: true });

  const response = await request.get({ ...baseOptions });

  expect(response.example).toEqual(true);
});

推荐答案

//MOCK

let mockGetTimeOutId = jest.fn();
jest.mock('../request-timeout', () => {
    return jest.fn().mockImplementation((ms) => {
        let timeoutId = undefined;
        return {
            start: () => new Promise((resolve, reject) => {
                timeoutId = setTimeout(() => reject(), ms);
            }),
            clear: () => mockGetTimeOutId(timeoutId),
        }
    })
});

//测试

it('should clear the timeout following a successful response', async () => {
    nock('http://example.com')
        .get('/')
        .reply(200, { example: true });

    expect(mockGetTimeOutId).toHaveBeenCalledTimes(0);

    const response = await request.get({ ...baseOptions });

    expect(mockGetTimeOutId).toHaveBeenCalledTimes(1);
    expect(response.example).toEqual(true);
});

这篇关于开玩笑-如何模拟模块使用的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆