mardi 16 janvier 2018

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?

Aucun commentaire:

Enregistrer un commentaire