I’m trying to test an api. Here’s how it works.
- It will create 20 documents in the database (for loop). Like this one.
{
"_id": {
"$oid": "5bfa89a329359318e15a4acc"
},
"text": "praiseworthy",
"bumped_on": {
"$date": "2018-11-25T11:38:11.121Z"
},
"reported": false,
"delete_password": "123",
"created_on": {
"$date": "2018-11-25T11:38:11.121Z"
},
"replies": [],
"__v": 0
}
- Then it will get the first 10 documents through the
it('GET')
test where it will be save inbody
variable as array. - For each object in that array it has a
replies
property the same to the one above. Then for each object it should call/post a reply. Wherein it will add document/s (an object) inside thereplies
. The number of objects inside thereplies
will depend the result of thelet randomNumberOfReplies = Math.floor(Math.random() * 5) + 1
. So, it should like this:
replies: [{
"_id": {
"$oid": "5bfa8d79f17ea01e886af976"
},
"text": "priceless",
"delete_password": "222",
"reported": false,
"created_on": {
"$date": "2018-11-25T11:54:33.235Z"
}
}]
Here is the actual code for test:
const chaiHttp = require('chai-http');
const chai = require('chai');
const superb = require('superb');
const mongoose = require('mongoose');
const request = require('request');
const assert = chai.assert;
const server = require('../server');
chai.use(chaiHttp);
describe('API ROUTE FOR /api/threads/:board', function() {
for (let i = 0; i < 20; i++) {
it('POST', (done) => {
chai.request(server)
.post('/api/threads/211')
.send({ text: superb.random(), delete_password: '123' })
.end((err, res) => {
if (err) done(err);
assert.equal(res.status, 200);
// done();
})
});
}
it('GET', function(done) {
chai.request(server)
.get('/api/threads/xx')
.end(function(err, result){
let body = result.body; // returns an array of objects
body.forEach((elem) => {
let randomNumberOfReplies = Math.floor(Math.random() * 5) + 1;
for (let i = 0; i < randomNumberOfReplies; i++ ){
chai.request(server)
.post('/api/replies/new')
.type('form')
.send({ text: superb.random(), delete_password: '222', thread_id: elem._id })
.end((err, res) => {
if (err) console.log(err);
// console.log(res);
// done();
})
}
})
console.log('done');
done();
})
});
})