|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var express = require('express'), |
| 4 | + request = require('supertest'), |
| 5 | + bodyParser = require('body-parser'), |
| 6 | + expect = require('chai').expect; |
| 7 | + |
| 8 | +// Add xml parsing to bodyParser. |
| 9 | +// In real-life you'd `require('body-parser-xml')`. |
| 10 | +require('./index.js')(bodyParser); |
| 11 | + |
| 12 | +describe('XML Body Parser', function() { |
| 13 | + var app; |
| 14 | + |
| 15 | + var createServer = function(options) { |
| 16 | + app = express(); |
| 17 | + app.use(bodyParser.xml(options)); |
| 18 | + app.post('/', function(req, res) { |
| 19 | + res.status(200).send({ parsed: req.body }); |
| 20 | + }); |
| 21 | + }; |
| 22 | + |
| 23 | + beforeEach(function() { |
| 24 | + app = null; |
| 25 | + }); |
| 26 | + |
| 27 | + it('should parse a body with content-type application/xml', function(done) { |
| 28 | + createServer(); |
| 29 | + |
| 30 | + request(app) |
| 31 | + .post('/') |
| 32 | + .set('Content-Type', 'application/xml') |
| 33 | + .send('<customer><name>Bob</name></customer>') |
| 34 | + .expect(200, { parsed: { customer: { name: ['Bob'] } } }, done); |
| 35 | + }); |
| 36 | + |
| 37 | + it('should parse a body with content-type text/xml', function(done) { |
| 38 | + createServer(); |
| 39 | + |
| 40 | + request(app) |
| 41 | + .post('/') |
| 42 | + .set('Content-Type', 'text/xml') |
| 43 | + .send('<customer><name>Bob</name></customer>') |
| 44 | + .expect(200, { parsed: { customer: { name: ['Bob'] } } }, done); |
| 45 | + }); |
| 46 | + |
| 47 | + it('should accept xmlParseOptions', function(done) { |
| 48 | + createServer({ |
| 49 | + xmlParseOptions: { |
| 50 | + normalize: true, // Trim whitespace inside text nodes |
| 51 | + normalizeTags: true, // Transform tags to lowercase |
| 52 | + explicitArray: false // Only put nodes in array if >1 |
| 53 | + } |
| 54 | + }); |
| 55 | + request(app) |
| 56 | + .post('/') |
| 57 | + .set('Content-Type', 'text/xml') |
| 58 | + .send('<CUSTOMER><name> Bob </name></CUSTOMER>') |
| 59 | + .expect(200, { parsed: { customer: { name: 'Bob' } } }, done); |
| 60 | + }); |
| 61 | + |
| 62 | + it('should ignore non-XML', function(done) { |
| 63 | + createServer(); |
| 64 | + |
| 65 | + request(app) |
| 66 | + .post('/') |
| 67 | + .set('Content-Type', 'text/plain') |
| 68 | + .send('Customer name: Bob') |
| 69 | + .expect(200, { parsed: {} }, done); |
| 70 | + }); |
| 71 | + |
| 72 | + it('should reject invalid XML', function(done) { |
| 73 | + createServer(); |
| 74 | + request(app) |
| 75 | + .post('/') |
| 76 | + .set('Content-Type', 'text/xml') |
| 77 | + .send('<invalid-xml>') |
| 78 | + .expect(400, done); |
| 79 | + }); |
| 80 | +}); |
0 commit comments