Jest 模拟调用真实客户端而不是模拟

时间:2021-04-16 14:13:51

标签: javascript node.js unit-testing jestjs

我试图在以下测试中模拟对我们实际短信客户端的调用:

message.test.js

/**
 * @jest-environment node
 */

import { createMocks } from "node-mocks-http";
import handleFormSubmit from "../../../../pages/api/messages";

describe("/api/messages", () => {
  test("sends a user to the error page if govnotify errors", async () => {
    jest.mock("../../../../src/use_cases/send_text_message", () => ({
      __esModule: true,
      default: () => 
        jest.fn().mockReturnValue({error: "aFakeTestingError"})
    }))

    const { req, res } = createMocks({
      method: "POST",
      body: {phoneNumber: "aFakePhoneNumber",
      name: "aFakeName",},
    });

    await handleFormSubmit(req, res);
    expect(res._getRedirectUrl()).toBe("/text_service_error")
    expect(res.statusCode).toBe(302);
  })
});

这是我要模拟 sendTextMessage 函数的测试文件。

messages.js

import sendTextMessage from "../../src/use_cases/send_text_message";
import { getNotifyClient } from "../../src/dependencies";

export default async (req, res) => {

  if (!(req?.body?.phoneNumber && req?.body?.name)) {
    res.redirect("/text_service_error")
    return;
  }

  const notifyClient = getNotifyClient();
  const result = await sendTextMessage(notifyClient)(req.body.phoneNumber);
  console.log(result)
  if (result.error) {
      res.redirect("/text_service_error")
      return;
    }

  res.redirect("/text_service_confirm");
};

sendTextMessage 函数来自另一个文件,如下所示:

send_text_message.js

import CONSTANTS from "../constants";

const sendTextMessage = (notifyClient) => async (phoneNumber) => {
  let result;
  try {
    result = await notifyClient.sendSms(
      CONSTANTS.GOV_NOTIFY_TEMPLATE_ID,
      phoneNumber
    );
  } catch (err) {
    result = { error: { message: "Actual production error" } };
  }
  return result;
};

export default sendTextMessage;

每次运行测试时,我都会收到一条通知,说 sms 客户端尝试发送短信,而不是使用模拟和错误。我不是在嘲笑 getNotifyClient();,因为我认为嘲笑整个 sendTextMessage 函数就足够了?

0 个答案:

没有答案