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

橙三吉。 提交于 2019-12-11 15:24:37

问题


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.

来源:https://stackoverflow.com/questions/46886850/how-to-test-a-get-post-api-with-mocha-and-chai-using-authentication

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!