Как заглушить функцию, которая была вызвана по запросу API в node js с помощью sinon - PullRequest
0 голосов
/ 12 апреля 2020
//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);
}

Я пишу модульное тестирование в node js, используя sinon.
Я хочу, чтобы заглушка UnoModel.getGameInfo возвращала {id:'123456789012'}, когда я нажал /someid/info rest api.

Я написал тестовый пример, как показано ниже.

//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();
    });
});

Но я я получаю код состояния 404.
Я пытался утешить данные. На самом деле его выборка из БД. Он не возвращает указанное значение для заглушки.
Может кто-нибудь помочь мне с этим?
Есть ли другой способ сделать это?

1 Ответ

0 голосов
/ 13 апреля 2020

должно работать. Например,

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 с отчетом о покрытии:

  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 |                   
------------------|---------|----------|---------|---------|-------------------

исходный код: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61172026

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...