将 Jest 与 Firebase HTTP 云函数结合使用

问题描述

我正在用 Jest 进行单元测试。我对单元测试 firebase 云功能特别感兴趣。我有一个可行的解决方案,但因为我是 Jest 和单元测试的新手,所以我不确定这是否是最好的方法

我有几个简单的 firebase 函数,用于检查拼写错误(不使用任何其他 firebase 服务 - 非常简单)。它们看起来像这样:

const functions = require("firebase-functions");
const SpellChecker = require("spellchecker");

exports.isWordMispelled = functions.https.onRequest((request,response) => {
  const lang = request.query.lang ? request.query.lang : "en";
  const word = request.body.word;
  SpellChecker.setDictionary(lang);
  return response.send(isWordMispelled(word));
});

const isWordMispelled = (word) => {
  const spelling = SpellChecker.isMisspelled(word);
  return spelling;
};

//

exports.checkSpelling = functions.https.onRequest((request,response) => {
  const lang = request.query.lang ? request.query.lang : "en";
  const text = request.body.text;
  SpellChecker.setDictionary(lang);
  return response.send(checkSpelling(text));
});

const checkSpelling = (text) => {
  const mispellingLocations = SpellChecker.checkSpelling(text);
  const errorWords = [];
  for (const mispellingStartStop of mispellingLocations) {
    const errorWord = text.slice(
      mispellingStartStop.start,mispellingStartStop.end
    );
    errorWords.push(errorWord);
  }
  return errorWords;
};

然后我有一些这样的测试设置:

const tester = require("firebase-functions-test")();
const functions = require("../index.js");

const res = {
  send: (response) => {
    return response;
  },};

test("mispelled word",async () => {
  const req = { query: { lang: "en" },body: { word: "blarg" } };
  const response = await functions.isWordMispelled(req,res);
  expect(response).toBe(true);
});

test("correctly spelled word",body: { word: "hello" } };
  const response = await functions.isWordMispelled(req,res);
  expect(response).toBe(false);
});

test("Text with mispelling",async () => {
  const req = {
    query: { lang: "en" },body: { text: "hellow my name is blargenfarb" },};
  const response = await functions.checkSpelling(req,res);
  expect(response).toStrictEqual(["hellow","blargenfarb"]);
});

test("correctly spelled text",body: { text: "wow such great testing" },res);
  expect(response).toStrictEqual([]);
});

tester.cleanup();

这些都有效并且所有测试都通过了。 我的问题是在 firebase 函数中返回响应对象似乎很奇怪。我通常不会这样做,但这是我将响应结果传递回测试的唯一方法。我尝试使用 supertest 并且如何将它与 express 一起使用是有意义的,但我无法使用云函数解决它。有什么建议或意见吗?

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...