Jest:如何模拟函数并测试它被调用?

时间:2018-01-17 01:14:18

标签: javascript testing jest

我有一个循环遍历数组并为每个元素发出HTTP请求的方法:

文件processor.js

const chunkFile = (array) => {
  return array.map(el => {
    sendChunkToNode(el);
  });
};

const sendChunkToNode = (data) =>
  new Promise((resolve, reject) => {
    request.post(...);
  });

export default {
  chunkFile,
  sendChunkToNode,
};

我已经对sendChunkToNode进行了测试:

describe("sendChunkToNode", () => {
  beforeEach(() => {
    // TODO: figure out how to mock request with certain params
    nock(API.HOST)
      .post(API.V1_UPLOAD_CHUNKS_PATH)
      .reply(201, {
        ok: true
      });
  });

  it("makes a POST request to /api/v1/upload-chunks", async () => {
    const response = await FileProcessor.sendChunkToNode(
      1,
      "not_encrypted",
      "handle"
    );
    expect(response).toEqual({ ok: true });
  });
});

我现在想要对chunkFile进行测试。在测试中,我只想测试sendChunkToNode是否被调用了不同的元素。像这样:

describe("chunkFile", () => {
  it("calls sendChunkToNode with each element", async () => {
    expect(sendChunkToNode).toBeCalledWith(1) //<--- I made the toBeCalledWith method up
    expect(sendChunkToNode).toBeCalledWith(2) //<--- I made the toBeCalledWith method up
    chunkFile([1,2]);
  });
});

有没有办法在Jest中做到这一点?

1 个答案:

答案 0 :(得分:0)

你编写它的方式,你应该只做一个循环并执行nock的次数与数组中元素的数量一样多。然后,你拨打chunkFile();如果存在未决的nock请求,则表示出现问题并且测试将失败。

test('...', () => {

  const someArray = ['a', 'b', 'c']; // someArray.length == 3
  someArray.forEach(element => {
    nock(...); // set up nock using element value
  });

  // if the nock interceptors you set up don't match any request, it will throw an error
  chunkFile(someArray); 
});