javascript - Jest 测试没有通过任何参数(变为“未定义”)
问题描述
编辑:变量由于某种原因username
变成了。undefined
我也尝试传递其他变量,但它们都没有像console.log()
.
我有一个用于测试我的 API的笑话文件(“index.test.js”) :
'use strict';
const request = require('supertest');
const app = require('./index');
describe('Test login', () => {
test('POST /login', () => {
return request(app)
.post('/login')
.send({username: 'preset1'}) //suggestion by @acincognito
.expect(301)
});
});
以及我的 nodejs 文件(“index.js”)中的相应 POST 路由:
...
function contains(arr, key, val) {
for (var i = 0; i < arr.length; i++) {
if(arr[i][key] === val) {
return true
};
}
return false;
}
app.post("/login", async (req, res) => {
try {
var username = req.body.username;
const data = await readFile("results.json");
var json = JSON.parse(data);
if (contains(json, "name", username) === true){
...
return res.redirect(301,"/");
} else {
return res.redirect(401,"/");
}
} catch (error) {
return res.redirect("/");
}
});
JSON 文件(“results.json”)具有以下格式:
[
{"name":"preset1","otherstuff":[]},
...
{"name":"preset5","otherstuff":[]}
]
我收到错误消息:
expected 301 "Moved Permanently", got 401 "Unauthorized"
注意:当我在本地服务器上手动运行代码时,一切正常,这似乎与测试的输出相矛盾。
解决方案
将 a 添加console.log(json)
到您的app.post
函数中以查看解析的内容。
在查看文档后supertest
: 显然.set('username','preset1')
是用于在您的请求中设置标头,但根据您app.post
username
在请求正文中的内容,因此请尝试.send({username: 'preset1'})
.
推荐阅读
- python - 当我无法访问实例化代码时,如何专门化对象实例?
- android - 调试器与运行时中使用的不同 packageName 的问题
- excel-formula - 将特定值与excel中的单元格值分开?
- java - 使用多维数组反转数组顺序时的 ArrayIndexOutOfBound 异常:
- c# - Serilog.Exception 解构器的 JSON 配置
- javascript - 如何在javascript中为事件发送2个参数
- javascript - 如何在具有速度属性的悬停时立即停止滑动滑块自动播放,而不需要很长时间停止自动播放?
- java - java - 如何使用Java中的两个循环迭代从二维列表中删除一个元素
- node.js - Nodejs 安全 MQTT 连接
- php - 配置 CakePhp 以使用 SMTP 发送邮件