I have an express.js
post function which works fine for receiving and processing a file.
I'm trying to write a jasmine
unit-test which simulates the same thing using fs
& request
.
const request = require("request")
const fs = require("fs")
const app = require("../app.js")
const base_url = "http://localhost:3002/"
var wordFile = fs.readFileSync(__dirname + '/test.docx', 'utf8')
describe("POST a word file to /word", function() {
it("parses the word file, and returns an array of components", function(done) {
request({
url: base_url + "word",
method: "POST",
json: true,
headers: {
"content-type": "multipart/form-data",
},
body: wordFile
}, function (error, response, body) {
expect(response.statusCode).toBe(200)
done()
}
)
})
})
I get back a 500 error but when I use the following upload view on my app it works fine:
<form action="/mediaDev/word" method="post" enctype="multipart/form-data">
<input type="file" name='doc' placeholder="Select file"/>
<br/>
<button>Upload</button>
</form>
Is this problem related to the fact that I'm reading the file as utf8, or something else?
In your form you are posting to /mediaDev/word
whereas in your test you are posting to just /word
. Check this is correct.
You are also not following the request.js documented examples for sending multipart form data , which for your case would look like this:
var formData = {
doc: fs.createReadStream(__dirname + '/test.docx', {encoding:'utf8'})
}
request.post({url: base_url + "word", formData: formData}, function(error, repsonse, body) {
expect(response.statusCode).toBe(200)
done()
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.