[英]Jest test is not passing through any parameters (becomes 'undefined')
編輯:變量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"
注意:當我在本地服務器上手動運行代碼時,一切正常,這似乎與測試的 output 相矛盾。
將console.log(json)
添加到您的app.post
function 以查看解析的內容。
查看supertest
的文檔后:顯然.set('username','preset1')
用於在您的請求中設置標頭,但根據您的app.post
username
在請求正文中,因此請嘗試.send({username: 'preset1'})
。
我需要將 Javascript Object 編碼為字符串。
function serialize(obj){
return Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
}
// Code from : https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object
代替:
.send({username: 'preset1'})
用。。。來代替:
.send(serialize({username: 'preset1'}))
編輯:這不適用於所有參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.