node.js - Jest Mocking promise not working with error Cannot read property 'then' of undefined in ExpressJS
问题描述
我正在尝试为我的 ExpressJS 应用程序实施测试。谷歌搜索后我找不到任何解决方案,请帮助并拯救我的一天......!
我得到的错误。
TypeError: Cannot read property 'then' of undefined
6 | const arg1 = req.query.arg1;
7 | const arg2 = req.query.arg2;
> 8 | model.getExceptions(arg1, arg2, arg3)
测试文件如下
_test_/file.test.js:
import { getExceptions } from '../file';
jest.mock('../model');
describe('file.js', () => {
test('testing file...', () => {
const req = {query: {arg1: 'SOME'}};
const resp = {};
expect(getExceptions(req, 'dd', resp)).toHaveLength(1);
expect(getExceptions(req, 'ssd', resp)).toBe({test: 10});
});
})
模拟文件:
_mocks_/model.js
const model = {
getExceptions: (arg1, arg2, arg3) => {
return new Promise((resolve, reject) => {
process.nextTick(
() =>
arg1
? resolve({test: 110})
: reject({
error: 'not found.',
})
);
})
}};
export default model;
要测试的代码文件:
文件.js
export const getExceptions = (req, res, next) => {
const arg1 = req.query.arg1;
const arg2 = req.query.arg2;
model.getExceptions(arg1, arg2, req.arg3)
.then(([rows]) => res.write(rows))
.catch(next);
};
模型.js
const model = {
getExceptions: (arg1, arg2, arg3) => {
try {
return db.runQuery(qryName, [arg1, arg2, arg3]); // Custom function
} catch (e) {
throw new GatewayTimeoutError(e.message);
}
}
};
export default model;
如果需要更多详细信息,请告诉我。谢谢...
解决方案
最后我找到了答案。我保留这个问题,以防有人遇到类似问题并寻找解决方案。
这是一个非常简单的错误 - 模拟文件夹应该带有双破折号。
正确一:
__mocks__
不正确的一个:
_mocks_
推荐阅读
- ios - 为什么 ViewController 只占屏幕的一半?
- sql - 如何在oracle中将两个结果列合并到具有交替结果的列中?
- xamarin - 如何使我的 Xamarin 应用程序的 Android 项目以 MainApplication.cs 而不是 MainActivity.cs 开头
- r - 将 xlsx 与 R jupyter notebook 一起使用
- botium-box - 如何在botium中使用带有话语文件的变量
- dataframe - 如何在列上使用 pyspark min max 函数
- linux - 从主机到 docker 容器中的 conan-repository 的连接问题
- c# - 从 EF 视图到 EF 表的关系
- html - 如何在网页中包含示例 html 代码
- python - 我的代码使用超过 25GB 的内存和崩溃