должно работать. Например,
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