模拟嵌套函数的最佳方法是什么?

时间:2018-09-24 19:24:39

标签: google-cloud-functions jestjs

考虑功能

exports.projectNotifyLaunch = (admin, functions) => {
  return functions.database.ref("/projects/{pid}").onCreate(snap => {

    const { title } = snap.val();

    const notification = {
      title: `${title} just launched!`,
      body: `We just heard about a new cryptocurrency project called ${title}`
    };

    return admin.messaging().sendToTopic("premium", { notification });
  });
};

我应该如何模拟诸如

之类的深层嵌套函数

functions.database.ref("/projects/{pid}").onCreate(snap => {});

admin.messaging().sendToTopic("premium", { notification });

在开玩笑吗?我想触发snap=>{}回调并针对notification的值进行断言。

我能够做到这一点

这有效,但是很冗长。我想知道是否有更好的方法,或者Jest尚不了解的某种测试。

describe("send notification to premium users on new project", () => {
  // INPUTS
  const snap = {
    val: () => ({
      title: "Test Title"
    })
  };

  const functions = {
    database: {
      ref: () => ({
        onCreate: callback => callback(snap)
      })
    }
  };

  // outputs

  let topicStub = null;
  let notificationStub = null;

  const admin = {
    messaging: () => ({
      sendToTopic: (topic, notification) => {
        topicStub = topic;
        notificationStub = notification;
      }
    })
  };

  projectNotifyLaunch(admin, functions);

  test("title is correct", () => {
    expect(notificationStub.notification.title).toBe(
      "Test Title just launched!"
    );
  });

  test("topic is premium", () => {
    expect(topicStub).toBe("premium");
  });
});

0 个答案:

没有答案