首页 > 解决方案 > Nock 不拦截 http 请求

问题描述

我目前正在使用node-fetchandnock用于位于 Angular 项目之上的快速服务器。

我有以下正在调用 api 的中间件:

export const middleware = async(response: any) => {
    try {
        const result = await fetch(url).then(res => res.json())
        return response.status(200).json(result);
    } catch(err) {
        logger.error({eventId: 'get-content', err});
        return response.status(500)
    }
}

我的测试如下:

describe('API service', () => {
    let response, scope;
    beforeEach(() => {
        response = {
            status(s) { this.statusCode = s; return this; },
            json(result) { this.res = result; return this; },
        };
    })

    afterEach(() => {
        nock.restore();
    })

    it('should return a 200 response from successful call api', (done) => {
        scope = nock(url)
            .get(/.*/)
            .reply(200, {data: 'content'})

        middleware(response).then(data => {
            expect(response.status).toEqual(200);
            expect(response.data).toEqual('content');
            scope.isDone();
            done();
        })
    })
})

然而, nock 并没有模拟data来自中间件函数的响应。相反,我必须使用scope它来访问它的参数。

中间件函数的行为就好像 nock 从未嘲笑过它的响应。为什么会出现这种情况?我缺少配置吗?

我正在使用 karma runner 进行测试。

标签: javascriptnode.jsunit-testingtestingkarma-jasmine

解决方案


Nock 通过覆盖 Node 的 http.request 函数来工作。此外,它也覆盖了 http.ClientRequest 以覆盖直接使用它的模块。

不幸的是,它似乎fetch没有使用http.requesthttp.ClientRequest意味着请求永远不会被nock.

更好的方法可能是fetch使用诸如fetch-mock.


推荐阅读