首页 > 解决方案 > 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"

注意:当我在本地服务器上手动运行代码时,一切正常,这似乎与测试的输出相矛盾。

标签: javascriptnode.jstestingjestjssupertest

解决方案


将 a 添加console.log(json)到您的app.post函数中以查看解析的内容。

在查看文档后supertest: 显然.set('username','preset1')是用于在您的请求中设置标头,但根据您app.post username在请求正文中的内容,因此请尝试.send({username: 'preset1'}).


推荐阅读