如何让 Jest 看到我为 MongoDB Stitch 编写的函数? [英] How to get Jest to see the functions I am writing for MongoDB Stitch?

查看:17
本文介绍了如何让 Jest 看到我为 MongoDB Stitch 编写的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试用 Stitch,这是一个来自 MongoDB 的无服务器/托管 JavaScript 环境.我的主要目的是帮助我学习现代 JavaScript,但我也在努力编写一个有用的应用程序.

I am trying out Stitch, a serverless/hosted JavaScript environment from MongoDB. My main purpose is to help me learn modern JavaScript, but I am trying to write a useful app as well.

我编写了以下函数,并将其保存在我的 Stitch 应用程序中.我相信这遵循了在 Stitch 中编写函数的记录方式,并且我已经从 Stitch 管理控制台对其进行了测试:

I have written the following function, and saved it in my Stitch app. I believe this follows the documented way to write functions in Stitch, and I have tested it from the Stitch administration console:

exports = function(query){
  const http = context.services.get("HTTP");
  const urlBase = context.values.get("stackOverflowApiUrl");
  const options = [
    'order=desc',
    'sort=activity',
    'site=stackoverflow',
    'q=' + encodeURIComponent(query),
    'user=472495',
    'filter=!--uPQ.wqQ0zW'
  ];

  return http
    .get({ url: urlBase + '?' + options.join('&') })
    .then(response => {
      // The response body is encoded as raw BSON.Binary. Parse it to JSON.
      const ejson_body = EJSON.parse(response.body.text());
      return ejson_body.total;
    });
};

这段代码非常简单——它获取一个 http 对象用于进行外部 API 获取,并获取一个用于联系的 URL urlBase 的配置值(解析为 https://api.stackexchange.com/2.2/search/excerpts) 然后调用 Stack Overflow Data API.这会针对我的用户运行搜索查询并返回结果数.

This code is pretty simple - it obtains an http object for making external API fetches, and obtains a configuration value for a URL urlBase to contact (resolving to https://api.stackexchange.com/2.2/search/excerpts) and then makes a call to the Stack Overflow Data API. This runs a search query against my user and returns the number of results.

到目前为止一切顺利.现在,我想在 Jest 中本地调用这个函数.为此,我在本地 Docker 容器中安装了 Node 和 Jest,并编写了以下测试函数:

So far so good. Now, I want to call this function locally, in Jest. To do this, I have installed Node and Jest in a local Docker container, and have written the following test function:

const callApi = require('./source');

test('Simple fetch with no user', () => {
    expect(callApi('hello')).toBe(123);
});

失败,出现以下错误:

~ # jest
 FAIL  functions/callApi/source.test.js
  ✕ Simple fetch with no user (3ms)

  ● Simple fetch with no user

    TypeError: callApi is not a function

      2 | 
      3 | test('Simple fetch with no user', () => {
    > 4 |     expect(callApi('hello')).toBe(123);
        |            ^
      5 | });
      6 | 

      at Object.<anonymous>.test (functions/callApi/source.test.js:4:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.418s
Ran all test suites.

(事实上我原以为它会失败,因为它包含一个 Jest 无法访问的全局对象 context.我稍后会研究如何模拟它,但现在 Jest 不能甚至根本看不到功能).

(In fact I was expecting it to fail, since it contains a global object context that Jest does not have access to. I will work out how to mock that later, but for now Jest cannot even see the function at all).

我怀疑我可以看到原因 - 在 Jest 介绍文档中,必须为 SUT 执行此操作:

I suspect I can see the reason - in the Jest introduction docs, one has to do this for the SUT:

module.exports = function() { ... }

然而,Stitch 文档似乎要求将函数定义为:

However the Stitch docs seem to require functions to be defined as:

exports = function() { ... }

我没有 JavaScript 背景,无法理解其中的区别.我可以在 Stitch 中尝试 module.exports,但我宁愿不这样做,因为这要么现在不起作用,要么在将来导致损坏.可以指示 Jest 在没有 module 前缀的情况下查看"​​裸 exports 吗?

I do not have a background in JavaScript to understand the difference. I could try module.exports in Stitch, but I would rather not, since this would either not work now, or cause a breakage in the future. Can Jest be instructed to "see" bare exports without the module prefix?

顺便说一下,我选择 Jest 是因为它很受欢迎,而且我的一些 JavaScript 同事也为它提供了担保.但是,我并不喜欢它,如果知道它更适合 Stitch 开发,我很乐意使用其他东西.

Incidentally, I have picked Jest because it is popular, and because some of my JavaScript colleagues vouch for it. However, I am not wedded to it, and would be happy to use something else if it is known to be better for Stitch development.

根据下面 jperl 的有用答案,我发现在 Stitch 中无法进行以下构造:

Following the useful answer from jperl below, I find that the following construction is not possible in Stitch:

module.exports = exports = function() {}

我也不能这样做:

exports = function() {}
module.exports = exports

如果我尝试其中一个,我会收到以下错误:

If I try either, I get the following error:

函数验证期间的运行时错误

runtime error during function validation

所以看起来我必须让 Jest 在没有 module.exports 的情况下工作,或者创建一个将 exports 版本导入到 module.exports 的胶水文件,Stitch 使用主文件,Jest 使用胶水导入器.

So it looks like I have to get Jest to work without module.exports, or create a glue file that imports the exports version into module.exports, with the main file being used by Stitch, and the glue importer being used by Jest.

推荐答案

我建议你阅读这篇线程.您认为它与 modules.exportsexports 的关系是正确的.问题是 module.exportsexports 首先指向同一个东西.所以这样的事情有效:

I suggest you to read this thread. And you're right in thinking it has to do with modules.exports vs exports. The thing is that module.exports and exports first point to the same thing. So something like this works:

//modify the same object that modules.exports is pointing to
exports.a = {}
exports.b = {}

但这不会:

exports = {}

为什么?因为现在 exports 指向了 module.exports 以外的东西,所以你所做的根本没有影响.

Why? Because now exports points to something else than module.exports so what you're doing has no effect at all.

在评论中进行了一些更新后,我们认为 Stitch 似乎不支持 Jest 所需的导出格式.

Following some updates in the comments, we came to the view that Stitch does not seem to support the export format that Jest requires.

这篇关于如何让 Jest 看到我为 MongoDB Stitch 编写的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆