【发布时间】:2019-12-23 03:50:51
【问题描述】:
我正在试用 Stitch,这是一个来自 MongoDB 的无服务器/托管 JavaScript 环境。我的主要目的是帮助我学习现代 JavaScript,但我也在尝试编写一个有用的应用程序。
我编写了以下函数,并将其保存在我的 Stitch 应用程序中。我相信这遵循了在 Stitch 中编写函数的文档化方式,并且我已经从 Stitch 管理控制台对其进行了测试:
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),然后调用堆栈溢出数据 API。这将对我的用户运行搜索查询并返回结果数。
到目前为止一切顺利。现在,我想在 Jest 中本地调用这个函数。为此,我在本地 Docker 容器中安装了 Node 和 Jest,并编写了以下测试函数:
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 甚至无法在全部)。
我怀疑我可以看到原因 - 在 Jest 介绍文档中,必须为 SUT 执行此操作:
module.exports = function() { ... }
然而,Stitch 文档似乎要求将函数定义为:
exports = function() { ... }
我没有 JavaScript 的背景来理解其中的区别。我可以在 Stitch 中尝试module.exports,但我宁愿不这样做,因为这要么现在不起作用,要么在未来造成损坏。可以指示 Jest 在没有 module 前缀的情况下“看到”裸露的 exports 吗?
顺便说一句,我之所以选择 Jest,是因为它很流行,而且我的一些 JavaScript 同事也支持它。但是,我并不喜欢它,如果已知它更适合 Stitch 开发,我很乐意使用其他东西。
更新
根据下面 jperl 的有用答案,我发现在 Stitch 中无法进行以下构造:
module.exports = exports = function() {}
我也不能这样做:
exports = function() {}
module.exports = exports
如果我尝试任何一个,我都会收到以下错误:
函数验证期间的运行时错误
所以看起来我必须让 Jest 在没有module.exports 的情况下工作,或者创建一个胶水文件,将exports 版本导入module.exports,主文件由 Stitch 使用,胶水导入器是被 Jest 使用。
【问题讨论】:
标签: javascript jestjs mongodb-stitch