【问题标题】:Mock network requests and validate sent request [closed]模拟网络请求并验证发送的请求 [关闭]
【发布时间】:2019-02-18 06:57:03
【问题描述】:

我想要一种模拟网络请求并能够检查/验证模拟 API 接收到的内容的方法。大多数模拟框架只允许您验证响应。

【问题讨论】:

    标签: node.js unit-testing mocking


    【解决方案1】:

    我认为sinon && sinon.spy() 正是您在使用stubbed 函数执行此API 调用或模拟(使用nock 库)API 调用本身之后所需要的。

    调用被监视的函数后,您可以使用spy.calledWith(arg1, arg2, ...); 检查调用该函数时使用了哪些参数。你还有其他有用的工具,比如它被调用了多少次,或者什么时候等等......

    【讨论】:

    • 我决定使用sinonmoxios(因为我使用的是axios)。
    【解决方案2】:

    您可以使用 nock 来模拟 API,它的工作原理是这样的。

    const expect = require('chai').expect;
    const nock = require('nock');
    describe('Get User tests', () => {
      beforeEach(() => {
        nock('https://api.github.com')
          .get('/users/octocat')
          .reply(200, response);
      });
    
      it('Get a user by username', () => {
    
      });
    });
    

    这里是更多详细信息的链接https://scotch.io/tutorials/nodejs-tests-mocking-http-requests#toc-testing-the-right-way

    【讨论】:

    • 这看起来不错,只是它依赖于使用chai 测试框架。我希望解决方案与框架无关。
    猜你喜欢
    • 2021-04-18
    • 2019-01-26
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2020-04-04
    • 2015-06-08
    相关资源
    最近更新 更多