在Express代码的Mocha测试中编码JSON POST数据



My Express代码在从Postman调用时运行良好,但在从Mocha调用时运行不佳。这让我相信我的Mocha测试没有正确设置POST请求标头中的数据(我对无参数的GET或POST没有问题,对带参数的GET也没有问题;只有带参数的POST没有问题(。

这是一个简单的代码,尽管我不会集中讨论这个,因为它来自Postman:

const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Our unit tests send POST data in JSON format
app.use(express.json());

// Helper function - common code
function ResplyWithSentence(object, adjective)
{
console.log('GET requestuest received: object = ' + object + '; adjective = ' + adjective);
let sentence = softwareUnderTest.MakeAsentence(object, adjective);
sentence = JSON.stringify(sentence);
response.status(200);
response.set('Content-Type', 'text/json');
response.send( sentence );
}

// Handling POST request with parameters
app.post("/makeSentenceParamsPost", (request, response) => {
const object    = request.body.object;
const adjective = request.body.adjective;
ResplyWithSentence(object, adjective);
})

以下是邮差发送的内容:

POST /makeSentenceParamsPost HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 88dfc7cc-427e-3248-ba93-286083d4c18d
{
"object": "cat",
"adjective": "sleepy"
}

这是Mocha:

it('should handle a POST request with parameters', async function(){
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:3000/makeSentenceParamsPost", false);      // false === synchronous/blocking
xhttp.setRequestHeader("Content-type", "application/json");
const object = 'hubris';
const adjective = 'pervasive';
let   postParameters = {'object': object,
'adjective': adjective};
xhttp.onreadystatechange = function(done) {
while(this.readyState != 4) ;       // wait until "request finished and response is ready"
assert.isObject(this);
assert(this.status == 200);
assert(JSON.parse(this.responseText)['sentence'] == `The ${object} is ${adjective}`);
done();
};
postParameters = JSON.stringify(postParameters);
xhttp.send(postParameters);
});

收到的响应是The undefined is undefined.

有人能告诉我我做错了什么吗?甚至如何调试?

使用现代JavaScript

我建议调查一下fetch。它相当于ES5,并使用Promises。它可读性更强,易于定制。

const fetch = require("node-fetch");
const first = 'hubris'; // can't use words like object, these are reserved.
const second = 'pervasive';
let postParameters = {'first': first,
'second': second};
const url = "http://example.com";
fetch(url, {
method : "POST",
body: postParameters,
// -- or --
// body : JSON.stringify({
// user : document.getElementById('user').value,
// ...
// })
}).then(
response => response.text() // .json(), etc.

assert.isObject(this);
assert(this.status == 200);
assert(JSON.parse(this.responseText)['sentence'] == `The ${object} is ${adjective}`);
done();
);

Type上的大写T解决了问题:

xhttp.setRequestHeader("Content-Type", "application/json");

最新更新