简体   繁体   中英

How to stub a function that was called on api request in node js using sinon

//routes.js
app.get('/:id/info',
    UnoController.getGameInfo,
    ...
);

//UnoController.js
async function getGameInfo(req, res) {
    data = await UnoModel.getGameInfo(req.params.id);
    if(data==null) return res.status(404).json({message:'Room Not Found'});
    res.json(data);
}


//UnoModel.js
exports.getGameInfo = async function (id) {
    return await mongodb.findById('uno', id);
}

I am writing unit testing in node js using sinon.
I want stub the UnoModel.getGameInfo to return {id:'123456789012'} , When i hit /someid/info rest api.

I wrote the test case like below.

//UnoApiTest.js
it('get game info with player payload and invalid room id', function (done) {
    sinon.stub(UnoModel, 'getGameInfo').resolves({ id: '123456789012' });
    request({
        url: 'http://localhost:8080/api/v1/game/uno/123456789012/info',
        headers: { 'x-player-token': jwt.sign({ _id: '123' }) }
    }, function (error, response, body) {
        expect(response.statusCode).to.equal(200);
        done();
    });
});

But i am receiving the statusCode as 404.
I tried to console the data. Its actually fetching from db. It doesn't returns the provided value for stub.
Can anyone help me with this?
Is there any other way to do this?

It should work. Eg

server.js :

const express = require('express');
const UnoController = require('./UnoController');
const app = express();

app.get('/api/v1/game/uno/:id/info', UnoController.getGameInfo);

module.exports = app;

UnoController.js :

const UnoModel = require('./UnoModel');

async function getGameInfo(req, res) {
  const data = await UnoModel.getGameInfo(req.params.id);
  if (data == null) return res.status(404).json({ message: 'Room Not Found' });
  res.json(data);
}

exports.getGameInfo = getGameInfo;

UnoModel.js :

// simulate mongodb
const mongodb = {
  findById(arg1, arg2) {
    return { name: 'james' };
  },
};
exports.getGameInfo = async function(id) {
  return await mongodb.findById('uno', id);
};

UnoApiTest.test.js :

const app = require('./server');
const UnoModel = require('./UnoModel');
const request = require('request');
const sinon = require('sinon');
const { expect } = require('chai');

describe('61172026', () => {
  const port = 8080;
  let server;
  before((done) => {
    server = app.listen(port, () => {
      console.log(`http server is listening on http://localhost:${port}`);
      done();
    });
  });
  after((done) => {
    server.close(done);
  });
  it('should pass', (done) => {
    sinon.stub(UnoModel, 'getGameInfo').resolves({ id: '123456789012' });
    request({ url: 'http://localhost:8080/api/v1/game/uno/123456789012/info' }, function(error, response, body) {
      expect(response.statusCode).to.equal(200);
      done();
    });
  });
});

API automation test results with coverage report:

  61172026
http server is listening on http://localhost:8080
    ✓ should pass


  1 passing (50ms)

------------------|---------|----------|---------|---------|-------------------
File              | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------------|---------|----------|---------|---------|-------------------
All files         |      80 |       50 |   33.33 |   85.71 |                   
 UnoController.js |   83.33 |       50 |     100 |     100 | 5                 
 UnoModel.js      |      50 |      100 |       0 |      50 | 4,8               
 server.js        |     100 |      100 |     100 |     100 |                   
------------------|---------|----------|---------|---------|-------------------

source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61172026

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