Last active
July 5, 2022 11:55
-
-
Save sr2ds/1786aaff13948c89f4efcb7124ce2222 to your computer and use it in GitHub Desktop.
Methods to make a simple automatic tests system to non-tdd systems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* code from: https://gist.github.com/sr2ds/1786aaff13948c89f4efcb7124ce2222 | |
* | |
* Author: David Silva | |
* Dependencies: expressJs, mongoose, mocha, chai and chaiHttp | |
* necessary run mocha command with --delay param | |
* | |
* how it works: | |
* this project will allow you to store the state of all requests | |
* and use it to do automatic tests | |
* | |
* how to setup: | |
* 1. Copy this file to your project folder | |
* 2. Import `logMiddleware` to your express app | |
* 3. Import `runGenericTests` to a test file | |
* 4. To navegate on system to generate call logs - will be used to tests | |
* 5. Run test with `mocha --delay` | |
* | |
* @todo: | |
* 1. Finish the implementation of the generic assertions | |
* 2. Improve dependences relation | |
* 3. Refactor to best comphrehension | |
*/ | |
/** | |
* Mongoose interface to manage Logs to can be used for tests | |
*/ | |
function logModel() { | |
try { | |
const db = require('./src/lib/db'); // file with mongoose connection returned | |
const Schema = db.Schema; | |
const logsSchema = new Schema({ | |
method: { type: String, trim: true }, | |
url: { type: String, trim: true }, | |
query: { type: Object, }, | |
params: { type: Object, }, | |
body: { type: Object, }, | |
response: { type: Object, }, | |
key: { type: String, unique: true }, | |
}) | |
return db.models.Logs || db.model('Logs', logsSchema) | |
} catch (error) { | |
} | |
} | |
/** | |
* Express midleware to store request and response data in a Log | |
* Import this method to your express app | |
* app.use(require('../../genericTests').logMiddleware); | |
* | |
*/ | |
logMiddleware = async (req, res, next) => { | |
try { | |
const model = logModel() | |
const { query, params, body, originalUrl, method } = req; | |
let oldSend = res.send | |
res.send = async (data) => { | |
const key = `${method}${originalUrl}${JSON.stringify(body)}${JSON.stringify(query)}${JSON.stringify(params)}` | |
const hash = require('crypto').createHash('sha256').update(key, 'binary').digest('hex'); | |
// @todo: think about this hash key - something with low cost can be better | |
try { | |
await new model({ | |
method, | |
url: originalUrl, | |
body, | |
query, | |
params, | |
response: JSON.stringify(data), | |
key: hash | |
}).save() | |
// console.log('REQUEST:', method, originalUrl, query, params, body) | |
// console.log('RESPONSE:', data) | |
} catch (error) { | |
} | |
res.send = oldSend | |
return res.send(data) | |
} | |
next() | |
} catch (error) { | |
console.log(error) | |
next() | |
} | |
} | |
/** | |
* Iterates over all logs, make request each one and compare response with expected response | |
* Need improvements | |
* Run this method to your test file - like test/generic-http-tests.spec.js | |
* require('../genericTests').runGenericTests() | |
* | |
*/ | |
runGenericTests = async () => { | |
/* dependences for test */ | |
const chai = require('chai'); | |
const chaiHttp = require('chai-http'); | |
chai.use(chaiHttp); | |
const expect = chai.expect; | |
const assert = require('assert'); | |
/* end - dependences for test */ | |
/* dependences about my application */ | |
const authConfig = require('config').config; | |
const jwt = require('jsonwebtoken'); | |
const User = require('./src/models/user-model'); | |
/* end - dependences about my application */ | |
/* get all logs */ | |
const model = logModel() | |
data = await model.find({}) | |
/* get some user to use jwt */ | |
const [user] = await User.find().limit(1).select('_id'); | |
const token = jwt.sign({ id: user._id }, authConfig.auth.secret, { expiresIn: 86400 }) | |
describe('running tests on all requests stored on log', () => { | |
data.forEach((item) => { | |
it(`test ${item.method}: ${item.url}`, async (done) => { | |
if (item.method === 'GET') { | |
chai.request('http://localhost:3000') | |
.get(item.url) | |
.auth(token, { type: 'bearer' }) | |
.end((error, res) => { | |
/** | |
* this compare if resquest and response are equals | |
* is simple and not a good way to compare but help | |
* @todo: compare attributes of response and expected response | |
*/ | |
const testResponseBody = JSON.stringify(res.body) | |
const logResponseBody = JSON.parse(item.response) | |
// need fix behavior of chai-http | |
if (testResponseBody != '[]' && logResponseBody.lenght) { | |
assert.equal(testResponseBody, logResponseBody) | |
} | |
done() | |
}) | |
} | |
}) | |
}) | |
}); | |
run() | |
} | |
module.exports = { logModel, logMiddleware, runGenericTests }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment