Made a stupid mistake. I used before() instead of beforeEach() to create and log in the user.
beforeEach(function (done) { // do stuff before each test });
afterEach() removed Users in db.
Here's the full solution, if anyone is interested:
beforeEach(function (done) { // Clear data before testing user1 = { name: 'Fake User', username: 'test', email: ' test@test.com ', password: 'password' }; user2 = { name: 'Fake User2', username: 'test2', email: ' test2@test.com ', password: 'password2' }; job = { email: ' job@test.com ' , title: 'Title' , description: 'Job description that is at least 60 characters with much detail' , apply: 'Application instructions' , company: 'Company' , location: 'Location' }; function createUser1(cb){ agent1 .post('/api/users') .send(user1) .expect(200) .end(function(err, res){ if ( err ) throw err; loginUser1.call(null, cb); }); } function loginUser1(cb){ agent1 .post('/api/session') .send({ email: user1.email , password: user1.password }) .expect(200) .end(function(err, res){ if ( err ) throw err; loggedInUser1 = res.body; cb(); }); } function createUser2(cb){ agent2 .post('/api/users') .expect(200) .send(user2) .end(function(err, res){ if (err) throw err; loginUser2.call(null, cb); }); } function loginUser2(cb){ agent2 .post('/api/session') .send({ email: user2.email , password: user2.password }) .end(function(err, res){ if ( err ) throw err; loggedInUser2 = res.body; cb(); }); } async.series([function(cb){ createUser1(cb); }, function(cb){ createUser2(cb); }], done); //working, but looks like shiet with callbacks // agent1 // .post('/api/users') // .send(user1) // .expect(200) // // end handles the response // .end(function(err, res) { // if (err) throw err; // // agent1 // .post('/api/session') // .send({ // email: user1.email // , password: user1.password // }) // .expect(200) // .end(function(err, res) { // if ( err ) throw err; // // loggedInUser1 = res.body; // // //login the 2nd user // agent2 // .post('/api/users') // .expect(200) // .send(user2) // // end handles the response // .end(function(err, res) { // if (err) throw err; // // agent2 // .post('/api/session') // .send({ // email: user2.email // , password: user2.password // }) // .end(function(err, res) { // if ( err ) throw err; // // loggedInUser2 = res.body; // // done(); // }); // }); // }); // }); }); afterEach(function (done) { User.remove() .execQ() .then(function(){ return Job.remove().execQ() }) .done(function(){ done(); }); });
agent1 is a request as a promised object.
var requestp = require("supertest-as-promised"); var agent1 = requestp.agent(app)
chovy
source share