How to test a get/post api with mocha and chai usi

2019-08-23 17:43发布

问题:

I am testing some get and post apis of my node js application using mocha and chai. So far, I have been running it in my localserver and the sample code for each of post and get api is given below :

process.env.NODE_ENV = 'test';
var mongoose = require("mongoose");
var db_model = require('../models/myproject.model');

var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../app');
var should = chai.should();
var expect = chai.expect;

chai.use(chaiHttp);


describe('First POST', ()=> {
    it('This is the first post', (done) => {
        chai.request(server)
    //chai.request('http://localhost:8000') //this also works
        .post('/data/myproject')
        .send(db_model)
        .end((err, res) => {
            //expect(true).to.be.true;
            expect(res.statusCode).to.equal(200);

        done();
        });
    });


});


describe('First GET', () => {
    it('This is the first get', (done)=> {
        chai.request(server)
        .get('/data/myproject')
        .end((err, res) => {
            //expect(true).to.be.true;
            expect(res.statusCode).to.equal(200);


        done();
        });

    });

}); 

Now, I need to run the above code from the actual server i.e http://myproject.webportal.com

My POST request will be passed following parameters :
1. id = "any_numeric_id"
2. name = "some_name"
3. authentication (username, password) is required.
4. content = {"k1":"v1", "k2", "v2"} // basically json data

My GET request for the same will be having only #1, #2 and #3 of the above list. Basically when I fire this url manually in the browser it looks like :
http://myproject.webportal.com/data/myproject?id=405&name=smith

How do I need to change my code to fit this requirement, I have gone through several links about this but getting confused and not able to get the result.

Can anybody please help me on this coding to give me a fair idea on how to do it properly?

Thanks.