有没有办法对端点数组进行设置?

is there a way to nock an array of endpoints?

我想从测试中抽象出客户端 API 的响应,我正在尝试为此提供帮助,例如:

class MockedClientApi {
  constructor() {
     this.nock = nock('https://client.domain.com');
  }

  getCountryInfo(country) {
    const endpoint = `/api/info/country/${country}`;
    return this.nock(endpoint).reply(200, responses.getCountryInfo);
  }
  getUserInfo(userId) {
    const endpoint = `/api/info/user/${userId}`;
    return this.nock(endpoint).reply(200, responses.getUserInfo);
  }
}

然后在测试中,我可以这样写:

let mockedRequests;
before('mock calls', () => {
  mockedRequests = [
    global.clientApi.getCountryInfo('GB'),
    global.clientApi.getUserInfo('ABC')
  ];
});

当然,这不像 nock 使用的链接

mockedRequests = nock('https://client.domain.com')
  .get(`/api/info/country/${country}`)
  .reply(200, responses.getCountryInfo)
  .get(`/api/info/user/${userId}`)
  .reply(200, responses.getUserInfo)

稍后我会这样做:

describe('when client API is called', () => {
    it('should call all mocked endpoints', () => {
        expect(mockedRequests.pendingMocks()).to.deep.equal([]);
    });
});

如何从动态 calls/single 调用进行链接?

我什至尝试想出一些行不通的想法,例如:

  mockedRequests = nock([
    global.clientApi.getCountryInfo('GB'),
    global.clientApi.getUserInfo('ABC')
  ]);

看起来您正在多次初始化 nock,以 multiple/different 个实例结束或改变原始实例。

在添加模拟请求的每个 class 函数中,您应该调用 nock 的“方法”函数的实例(getpost 等)来添加每个你想模拟的端点。然后你可以添加一个函数来获取 nock 的完整实例,或者只为你需要的每个断言创建辅助函数,比如 getPendingMocks().

const { expect } = require('chai');
const nock = require('nock');

class MockedClientApi {
    constructor() {
        this.mockedApi = nock('https://google.com')
    }

    getCountryInfo(country) {
        const endpoint = `/api/info/country/${country}`;

        return this.mockedApi.get(endpoint).reply(200, responses.getCountryInfo); // return might be unnecessary
    }

    getUserInfo(userId) {
        const endpoint = `/api/info/user/${userId}`;

        return this.mockedApi.get(endpoint).reply(200, responses.getUserInfo);
    }

    getPendingMocks() {
        return this.mockedApi.pendingMocks();
    }
}

describe('make tests', () => {
    let mockedClientApi;
    before('get mock', () => {
        mockedClientApi = new MockedClientApi();

        mockedClientApi.getCountryInfo();
        mockedClientApi.getUserInfo();
    });

    it('should call google', () => {
        expect(mockedClientApi.getPendingMocks()).to.deep.equal([]);
    });
});

最后你还应该考虑添加一个after功能来清除箭尾。