我想使用Javascript测试一个功能,该功能通过使用JavaScript FormData向服务器发出http发布请求。这是一个看起来像这样的最小示例:
import axios from "axios";
async function foo() {
let bodyFormData = new FormData();
bodyFormData.append("foo", "myfoo");
resp = await axios({
method: "post",
url: "https://postman-echo.com/post",
data: bodyFormData,
});
return resp;
}
describe("Test", () => {
it("foo test", async () => {
return foo().then(function (result) {
console.log(result);
// here some testing stuff ...
});
});
});
根据我的研究玩笑,无法使用FormData()。我该如何解决?我已经在SO上看到了一些解决方案,但是所有解决方案都以某种方式模拟了FormData,但是随之而来的问题是永远不会发送真正的请求,但是我想测试是否向工作中的真正服务器发送了真正的请求。我怎么能开玩笑呢?我也尝试过https://github.com/form-data/form-data,但它也无法正常工作
答案 0 :(得分:0)
实际上你需要像这样使用 supertest 模块
const supertest = require('supertest');
const app = require('../app');
const request = supertest(app)
describe('POST "/" root endpoint for login & authentication', function() {
it('/register method with missing parameter returns', function(done) {
request
.post('/register')
.send('username=john&password=12345') // x-www-form-urlencoded upload
.set('Accept', 'application/json')
.expect(200)
.end((err, res) => {
if(err) return done(err);
expect(res.body.message).toBe("Username or password is not specified");
return done();
});
});
});
您也可以查看此post