我无法测试接受纯文本作为输入的API。我的Api与邮递员的关系很好。现在,我想编写相同的单元测试用例。 API始终将文本作为对象接收。有趣的是,当我使用.set('Content-Type', 'text/plain')
时,API没有收到任何东西。丹吉!!!
这是我的测试用例代码:
const mystring = 'kashdjkasddavsdnbmavdjshgdjsagdj';
it('/myservice/v1/api/user(POST) should return user', () => {
return request(app.getHttpServer())
.post('/myservice/v1/api/user')
.set({
'Content-Type': 'text/plain',
'Accept': '*/*',
'Cache-Control': 'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Content-Length': '1956',
'Connection': 'keep-alive'
})
.send(mystring)
.expect(201)
.expect('user created successfully.');
});
我在服务器端收到的信息
{kashdjkasddavsdnbmavdjshgdjsagdj}
我对服务器端的期望
"kashdjkasddavsdnbmavdjshgdjsagdj"
-一个纯字符串。
mystring
仅供参考,实际内容有所不同。
答案 0 :(得分:1)
您应该使用bodyParser
模块中的Text body parser。这是一个最小的工作示例:
server.js
:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.text());
app.post('/myservice/v1/api/user', (req, res) => {
console.log(req.body);
res.status(201).send('user created successfully.');
});
module.exports = app;
server.test.js
:
const request = require('supertest');
const app = require('./server');
describe('59068158', () => {
const mystring = 'kashdjkasddavsdnbmavdjshgdjsagdj';
it('/myservice/v1/api/user(POST) should return user', (done) => {
request(app)
.post('/myservice/v1/api/user')
.set({
'Content-Type': 'text/plain',
Accept: '*/*',
'Cache-Control': 'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Content-Length': Buffer.byteLength(mystring),
Connection: 'keep-alive',
})
.send(mystring)
.expect(201)
.expect('user created successfully.', done);
});
});
集成测试结果:
PASS src/stackoverflow/59068158/server.test.js (12.724s)
59068158
✓ /myservice/v1/api/user(POST) should return user (88ms)
console.log src/stackoverflow/59068158/server.js:7
kashdjkasddavsdnbmavdjshgdjsagdj
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.151s
如您所见,您可以使用mystring
来获取客户端发送的req.body
的值。
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59068158