简体   繁体   中英

How to test path parameters of a GET request with NodeJS's supertest?

I've found examples how to test query parameters

eg:

/api/browser?parameter1=2341&parameter2=5663

but I couldn't find how to parametrize a test if I've a path parameter, an URL like this:

const ENDPOINT_DETAILS = "/api/browser/:parameter";
app.get(ENDPOINT_DETAILS, function (req, res) {

    logger.info("Endpoint called: " + ENDPOINT_DETAILS);
    var details = {}
    // ... magic
    res.send(details);
}

How should my test look like if I don't want to fix my parameter?

describe("returns details", function() {

    it("returns status 200", function(done) {

        var sampleData = "sample_detail";

        // this won't work
        restApi.get('/api/browser/:parameter')
            .set('Accept', 'application/json')
            .expect(200, { "text" : "Detail of " + parameter + " is: " + sample_text})
            .end(function(err, res) {
                if (err) throw err;
                done();
            });

    });
});

Is it possible to know the value of the parameter here, before restApi.get() is called?

You have to supply an actual number for :parameter . For example

restApi.get('/api/browser/1234')

The endpoint needs to be supplied with real values after all. req.params.parameter will then be 1234 in the endpoint function.

I'm not exactly sure what you mean with not fixing the parameter. Do you want to use a variable to make the test reusable for several parameters? Then I would simply do

let parameter = 1234;
restApi.get('/api/browser/' + parameter)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM