簡體   English   中英

用 FormData 開玩笑地測試請求(沒有模擬)

[英]Test request with FormData in jest (without mocking)

我想通過使用 javascript FormData 向服務器發出 http 發布請求來測試 function。 這是一個看起來像這樣的最小示例:

    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 上看到了一些解決方案,但所有這些解決方案都不知何故 mocking FormData 但問題是永遠不會發送真正的請求,但我想測試對真實服務器的真實請求是否在工作。 我怎么能開玩笑呢? 我也試過https://github.com/form-data/form-data但它也不起作用

實際上你需要使用這樣的超測試模塊

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();
      });
   });
});

你也可以查看這篇文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM