这是我的标题邮递员:
这是我邮递员的身体形式数据:
我已经在尝试这样
describe('test', function() {
describe('Get User Data', function() {
it.only('bla bla bla', function(done) {
// Send some Form Data
chai
.request(app)
.post('/user/login')
.send({ username: 'ihdisetiawan', password: 'testing123' })
.set('Accept', 'application/json')
.set('x-api-key', '1234567890')
.end(function(err, res) {
expect(res.status).to.equal(responseMessageCode.successOk);
// expect(res.password).to.equal("testing123");
done();
});
});
});
});
响应得到422
Uncaught AssertionError: expected 422 to equal 200
+ expected - actual
-422
+200
您需要使用multer中间件来处理具有multipart/form-data
内容类型的请求有效负载。此外,您的案例仅处理纯文本的多部分形式,应使用.none()
的multer
方法。
例如
server.ts
:
import express from 'express';
import multer from 'multer';
const app = express();
const port = 3000;
const upload = multer();
app.post('/user/login', upload.none(), (req, res) => {
console.log('username:', req.body.username);
console.log('password:', req.body.password);
console.log('content-type:', req.get('Content-Type'));
console.log('x-api-key:', req.get('x-api-key'));
res.sendStatus(200);
});
if (require.main === module) {
app.listen(port, () => {
console.log(`HTTP server is listening on http://localhost:${port}`);
});
}
export { app };
server.test.ts
:
import { app } from './server';
import request from 'supertest';
import { expect } from 'chai';
describe('test', () => {
describe('Get User Data', () => {
it('bla bla bla', (done) => {
request(app)
.post('/user/login')
.field({
username: 'ihdisetiawan',
password: 'testing123',
})
.set('x-api-key', '1234567890')
.end((err, res) => {
expect(res.status).to.equal(200);
done();
});
});
});
});
具有覆盖率报告的集成测试结果:
test
Get User Data
username: ihdisetiawan
password: testing123
content-type: multipart/form-data; boundary=--------------------------481112684938590474892724
x-api-key: 1234567890
✓ bla bla bla (47ms)
1 passing (66ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 86.67 | 50 | 50 | 86.67 |
server.ts | 86.67 | 50 | 50 | 86.67 | 16,17
-----------|---------|----------|---------|---------|-------------------