jeudi 12 novembre 2020

Always get undefined back when trying to test my koa2 API endpoint with mocha

as mentioned in the topic, I cannot only get undefined back from my api server when I trying to test it with mocha and chai, the framework for API is koa2. Please see codes attached

Testfile

var chai = require('chai');
var chaiHttp = require('chai-http');

chai.use(chaiHttp);
const app = require('../app')

const expect = chai.expect



describe( 'stat testing api', ( ) => {


    it('first api test', ( done ) => {
    chai.request(app.listen())
    .get('/api')
    .set('Accept', 'application/json')
    .end(( err, res ) => {
        

        expect(res.body).to.be.an('object')
      
        expect(res.body.data).to.be.an('json')
        done()
    })

}) })

The next is the server

var Koa = require("koa");
var router = require("koa-router")();
var jsonp = require('koa-jsonp');
var bodyParser = require('koa-bodyparser');



var app=new Koa();

app.use(jsonp());

app.use(bodyParser());

var api = require("./routes/api").routes();
var string = require("./routes/string").routes();
router.use("/api",api);
router.use(string);


app.use(router.routes());   
app.use(router.allowedMethods());


module.exports=app;

app.listen(3000);

Below is the api routes file

var router = require("koa-router")();

let result=JSON.stringify({message:"failed"});
router.get("/",async (ctx)=>{


ctx.body={message:"failed"}

})

module.exports=router;

No matter what testing tools I used i can only get undefined from the api server, however, when I input the localhost:3000/api I can see the json from the browser. Any ideas please? already spent more than 10 hours here and I am very new to testing frames. Thanks for you all

   Uncaught AssertionError: expected undefined to be a json
  at D:\programming\publift\test\firstapi.test.js:23:41
  at Test.Request.callback (node_modules\chai-http\node_modules\superagent\lib\node\index.js:716:12)
  at D:\programming\publift\node_modules\chai-http\node_modules\superagent\lib\node\index.js:916:18
  at IncomingMessage.<anonymous> (node_modules\chai-http\node_modules\superagent\lib\node\parsers\json.js:19:7)
  at endReadableNT (_stream_readable.js:1221:12)
  at processTicksAndRejections (internal/process/task_queues.js:84:21)

Aucun commentaire:

Enregistrer un commentaire