简体   繁体   中英

Jest: How to mock function and test that it was called?

I have a method that loops through an array and makes a HTTP request for each element:

file-processor.js

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

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

export default {
  chunkFile,
  sendChunkToNode,
};

I already have a test for 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 });
  });
});

I now want a test for chunkFile. In the test I just want to test that sendChunkToNode was called with the different elements. Something like this:

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]);
  });
});

Is there a way to do this in Jest?

The way you have it written, you should just make a loop and execute nock for as many times as the number of elements in the array. Then, you call chunkFile() ; if there are pending nock requests, that means something is wrong and the test will fail.

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); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM