diff --git a/jest.config.js b/jest.config.js index 6c8607f..60d54a6 100644 --- a/jest.config.js +++ b/jest.config.js @@ -17,4 +17,5 @@ module.exports = { testEnvironmentOptions: { url: 'http://localhost:5174', // replace with your test URL }, + testEnvironment: 'node', }; diff --git a/package.json b/package.json index 3c4fc46..7dddb34 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "serve": "vite preview", "vite": "vite", "server": "node server/server.js", - "test": "vitest", + "test": "NODE_ENV=test vitest", "coverage": "vitest run --coverage" }, "license": "MIT", @@ -58,6 +58,7 @@ "eslint-plugin-vue": "^8.7.1", "jest": "^29.5.0", "jsdom": "^21.1.0", + "sinon": "^15.0.1", "supertest": "^6.3.3", "typescript": "^4.9.5", "vite": "^4.1.4", diff --git a/server/controllers/accountController.js b/server/controllers/accountController.js index f00cd71..0dd9f87 100644 --- a/server/controllers/accountController.js +++ b/server/controllers/accountController.js @@ -48,8 +48,8 @@ accountController.loginWithoutCookie = (req, res, next) => { // showing the logged in user's projects before the mounting // of the home page accountController.userProjects = (req, res, next) => { - Users.findOne({username: res.locals.username}) - .then(data => { + Users.findOne({ username: res.locals.username }) + .then((data) => { res.locals.userProjects = data.project_ids; return next(); }) @@ -59,7 +59,7 @@ accountController.userProjects = (req, res, next) => { message: `could not find projects for user`, }); }); -} +}; // accountController.verifyUser = (req, res, next) => { // // write code here @@ -82,9 +82,8 @@ accountController.userProjects = (req, res, next) => { accountController.findUser = (req, res, next) => { // write code here // const { username } = req.body; - Users.find({ }) + Users.find({}) .then((data) => { - console.log(data) res.locals.username = data; return next(); }) @@ -92,7 +91,7 @@ accountController.findUser = (req, res, next) => { // if (err.message === `Username Doesn't Exist`) res.redirect("/signup"); return next({ log: err, - error: `error found in userController.verifyUser`, + error: `error found in userController.findUser`, }); }); }; diff --git a/server/controllers/authController.js b/server/controllers/authController.js index fbacd2e..d358d85 100644 --- a/server/controllers/authController.js +++ b/server/controllers/authController.js @@ -7,34 +7,40 @@ const authController = {}; authController.authenticate = (req, res, next) => { try { + // console.log('process.env.NODE_ENV', process.env.NODE_ENV); + console.log('INSIDE authController.authenticate'); const { ssid } = req.cookies; //decoded becomes {id,username} const decoded = jwt.verify(ssid, privateKey); res.locals.username = decoded.username; res.locals.id = decoded.id; - console.log('res.locals.username from decoded', res.locals.username) + console.log('res.locals.username from decoded', res.locals.username); // res.append('Access-Control-Allow-Origin', ['localhost:5173']) // res.locals.userInfo = decoded; + console.log('INSIDE authController.authenticate 2'); return next(); // res.status(200).json(decoded); } catch (err) { - return next(err); + return next({ + log: `authController.authenticate failed: ${err}`, + message: `Testing123, hi Sean`, + }); } }; authController.sign = (req, res, next) => { - console.log('res.locals', res.locals) + console.log('res.locals', res.locals); try { const { username, id } = res.locals; const token = jwt.sign( { username, - id + id, }, privateKey, { expiresIn: '6h' } ); - console.log(token) + console.log(token); res.locals.token = token; return next(); } catch (err) { diff --git a/server/controllers/projectController.js b/server/controllers/projectController.js index 313fe9e..e12de18 100644 --- a/server/controllers/projectController.js +++ b/server/controllers/projectController.js @@ -7,26 +7,34 @@ const projectController = {}; // already exists // if not, create a project; if so, update the project under that name with req.body.projectObject projectController.saveProject = (req, res, next) => { - console.log('res.locals.username in saveProject', res.locals.username); + console.log('INSIDE projectController.saveProject'); + console.log( + 'res.locals.username in projectController.saveProject: ', + res.locals.username + ); const { project_name, projectObject } = req.body; - Project.findOne({ project_name }).then(data => { + console.log('project_name in projectController.saveProject: ', project_name); + console.log( + 'projectObject in projectController.saveProject: ', + projectObject + ); + Project.findOne({ project_name }).then((data) => { if (!data) { console.log('making new project'); Project.create({ project_name, projectObject, - projectOwner: res.locals.username + projectOwner: res.locals.username, }) - .then(data => { - console.log('data.projectObject in saveProject', data.projectObject); + .then((data) => { res.locals.newProject = data.projectObject; res.locals.projectName = data.project_name; return next(); }) - .catch(err => { + .catch((err) => { next({ log: `projectController.saveProject failed, ${err}`, - message: `Can't save new project!` + message: `Can't save new project!`, }); }); } else { @@ -35,15 +43,15 @@ projectController.saveProject = (req, res, next) => { { project_name }, { projectObject: req.body.projectObject } ) - .then(data => { + .then((data) => { res.locals.newProject = data.projectObject; res.locals.projectName = data.project_name; return next(); }) - .catch(err => { + .catch((err) => { next({ log: `projectController.saveProject failed, ${err}`, - message: `Can't update project!` + message: `Can't update project!`, }); }); } @@ -53,42 +61,38 @@ projectController.saveProject = (req, res, next) => { // updates project_ids of of User who is saving a project // if it already exists in their projects array, it is not added projectController.userQuery = (req, res, next) => { + console.log('projectController.userQuery'); User.findOneAndUpdate( { username: res.locals.username }, { $addToSet: { project_ids: res.locals.projectName } }, { new: true } ) - .then(data => { - console.log('user projects', data.project_ids) + .then((data) => { res.locals.user = data; return next(); }) - .catch(err => { + .catch((err) => { next({ log: `projectController.userQuery failed, ${err}`, - message: `user already exists!` + message: `user already exists!`, }); }); }; // for retrieving projects ('open project' on frontend) projectController.getProject = (req, res, next) => { - console.log('In getProject controller') - console.log('Project Name',req.body.project_name ) - console.log('Username',res.locals.username ) Project.findOne({ project_name: req.body.project_name, - projectOwner: res.locals.username + projectOwner: res.locals.username, }) - .then(data => { - + .then((data) => { res.locals.project = data.projectObject; return next(); }) - .catch(err => { + .catch((err) => { next({ log: `projectController.getProject failed, ${err}`, - message: `Can't find project!` + message: `Can't find project!`, }); }); }; @@ -98,16 +102,15 @@ projectController.findProject = (req, res, next) => { // write code here // const { username } = req.body; Project.find({}) - .then(data => { - console.log(data); + .then((data) => { res.locals.username = data; return next(); }) - .catch(err => { + .catch((err) => { // if (err.message === `Username Doesn't Exist`) res.redirect("/signup"); return next({ log: err, - error: `error found in userController.verifyUser` + error: `error found in userController.verifyUser`, }); }); }; diff --git a/server/routes/accountRouter.js b/server/routes/accountRouter.js index 251c66c..e868edc 100644 --- a/server/routes/accountRouter.js +++ b/server/routes/accountRouter.js @@ -70,12 +70,8 @@ accountRouter.get( } ); -accountRouter.get( - '/logout', - cookieController.deleteCookie, - (req, res) => { - return res.sendStatus(200); - } -); +accountRouter.get('/logout', cookieController.deleteCookie, (req, res) => { + return res.sendStatus(200); +}); module.exports = accountRouter; diff --git a/server/routes/projectRouter.js b/server/routes/projectRouter.js index d1442be..06a537c 100644 --- a/server/routes/projectRouter.js +++ b/server/routes/projectRouter.js @@ -21,10 +21,10 @@ projectRouter.post( authController.authenticate, projectController.getProject, (req, res) => { - console.log('testing route') + console.log('testing route'); return res.status(201).json(res.locals.project); } -) +); projectRouter.get( '/find', @@ -32,9 +32,10 @@ projectRouter.get( // oAuthController.requestGitHubIdentity, (req, res) => { console.log('in find'); - return res.status(200).json(res.locals.username); + return res + .status(200) + .json({ hello: test, 'res.locals.usename': res.locals.username }); } ); - module.exports = projectRouter; diff --git a/server/server.js b/server/server.js index 8d2e408..33c67ca 100644 --- a/server/server.js +++ b/server/server.js @@ -18,8 +18,7 @@ const projectRouter = require('./routes/projectRouter'); // Connecting to MongoDB const mongoose = require('mongoose'); -const myURI = - 'mongodb+srv://prevue:prevue123@pvcluster.msrpd4m.mongodb.net/?retryWrites=true&w=majority'; +const myURI = process.env.MONGO_URI; const { MongoClient } = require('mongodb'); mongoose .connect(myURI, { @@ -27,10 +26,10 @@ mongoose useNewUrlParser: true, useUnifiedTopology: true, // sets the name of the DB that our collections are part of - dbName: 'prevueDB' + dbName: 'prevueDB', }) .then(() => console.log('Connected to Mongo DB.')) - .catch(err => console.log(err)); + .catch((err) => console.log(err)); // Global Middleware app.use(express.json()); @@ -56,7 +55,7 @@ app.use((err, req, res, next) => { const defaultErr = { log: 'Express error handler caught unknown middleware error', status: 400, - message: { err: 'An error occurred' } + message: { err: 'An error occurred' }, }; const errorObj = Object.assign({}, defaultErr, err); console.log(errorObj.log); diff --git a/src/store/state/stateIndex.ts b/src/store/state/stateIndex.ts index 1e164c4..dfa377b 100644 --- a/src/store/state/stateIndex.ts +++ b/src/store/state/stateIndex.ts @@ -9,23 +9,23 @@ const newState: State = { App: { componentName: 'App', children: ['HomeView'], - htmlList: [] + htmlList: [], }, HomeView: { componentName: 'HomeView', children: [], - htmlList: [] - } + htmlList: [], + }, }, routes: { - HomeView: [] + HomeView: [], }, componentNameInputValue: '', activeRoute: 'HomeView', activeComponent: '', selectedElementList: [], - projectName: 'Unititled-1', + projectName: 'Untitled-1', componentChildrenMultiselectValue: [], modalOpen: false, htmlElements: [], diff --git a/tests/integration/supertest.spec.js b/tests/integration/supertest.spec.js index e6669f7..f822b7d 100644 --- a/tests/integration/supertest.spec.js +++ b/tests/integration/supertest.spec.js @@ -1,17 +1,23 @@ const request = require('supertest'); const mongoose = require('mongoose'); const server = require('../../server/server'); +// const server = 'http://localhost:8080'; const accountRouter = require('../../server/routes/accountRouter'); const projectRouter = require('../../server/routes/projectRouter'); +<<<<<<< HEAD +const authController = require('../../server/controllers/authController'); +const jest = require('jest'); +const sinon = require('sinon'); +======= // remember to put back .env rather than using exposed URI //const myURI = needs connection string URI from env file +>>>>>>> dev beforeAll(async () => { // connect to MongoDB before all tests - await mongoose.connect(myURI, { - // await mongoose.connect(process.env.MONGO_URI, { + await mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); @@ -29,12 +35,77 @@ describe('/projects projectRouter', () => { projectOwner: 'testflynn5', }; +<<<<<<< HEAD + // make a testAccount + const testAccount = { + username: 'testflynn5', + id: '12345678', + project_ids: ['1'], + }; + + // in mock auth middleware, assign res.locals.username and res.locals.id to the username + // and id of testAccount + const mockAuth = (req, res, next) => { + res.locals.username = testAccount.username; + res.locals.id = testAccount.id; + console.log('we in mockAuth'); + return next(); + }; + + const middlewareIndex = server._router.stack.findIndex( + (layer) => layer.name === authController.authenticate + ); + + server._router.stack[middlewareIndex] = mockAuth; + + // const realAuth = authController.authenticate; + + describe('find a project, GET to /find', () => { + it('responds with 200 status', () => { + return request(server).get('/projects/find').expect(200); + }); + + it('should retrieve all projects from the database', () => {}); + }); + +======= +>>>>>>> dev describe('saving a project, POST to /saveProject', () => { it('responds with 201 status', () => { return request(server) .post('/projects/saveProject') .send(testProject) +<<<<<<< HEAD + .expect(400); + }); + + // it('should save a project to the database', () => {}); + // }); + + // describe('find a project, POST to /getProject', () => { + // it('responds with 201 status', () => {}); + + // it('should retrieve a project from the database', () => {}); + }); +}); + +describe('/users accountRouter', () => { + const testAccount = { + username: 'testflynn5', + id: '12345678', + project_ids: ['1'], + }; + + describe('POST / createUser', () => { + it('responds with 200 status', () => { + // return request(server).post('/users/createUser').expect(201); + }); + + it('creates an SSID cookie', () => { + // return request(server).post('/users/createUser').expect(201); +======= .expect(201); +>>>>>>> dev }); it('should save a project to the database', () => {}); @@ -47,6 +118,32 @@ describe('/projects projectRouter', () => { }); }); +<<<<<<< HEAD +// let authenticateStub; + +// beforeEach(() => { +// // create a stub for the authenticate function +// authenticateStub = sinon +// .stub(authController, 'authenticate') +// .callsFake((req, res, next) => next()); +// }); + +// afterEach(() => { +// // restore the original authenticate function +// authenticateStub.restore(); +// }); + +// mock the auth middleware +// jest.mock('../../server/controllers/authController', () => ({ +// authenticate: (req, res, next) => next(), +// })); +// const authenticate = (req, res, next) => { +// // Call the next middleware function without doing any authentication +// next(); +// jest +// .spyOn(require('../../server/controllers/authController'), 'authenticate') +// .mockImplementation(authenticate); +======= describe('/users accountRouter', () => { const testAccount = { username: 'testflynn5', @@ -60,3 +157,4 @@ describe('/users accountRouter', () => { }); }); }); +>>>>>>> dev diff --git a/tests/integration/supertest2.spec.js b/tests/integration/supertest2.spec.js new file mode 100644 index 0000000..0d9ef27 --- /dev/null +++ b/tests/integration/supertest2.spec.js @@ -0,0 +1,94 @@ +const request = require('supertest'); +const mongoose = require('mongoose'); +let server; +// const server = require('../../server/server'); +// const server = 'http://localhost:8080'; +const accountRouter = require('../../server/routes/accountRouter'); +const projectRouter = require('../../server/routes/projectRouter'); +const authController = require('../../server/controllers/authController'); +// const jest = require('jest'); +const sinon = require('sinon'); + +beforeAll(async () => { + // console.log('node cache', Object.keys(require.cache)); + // connect to MongoDB before all tests + await mongoose.connect(process.env.MONGO_URI, { + useNewUrlParser: true, + useUnifiedTopology: true, + }); +}); + +afterAll(async () => { + // disconnect from MongoDB after all tests + await mongoose.disconnect(); +}); + +let sandbox; +let authenticateStub; + +beforeEach(() => { + // create sinon sandbox to simplify working with fakes that need to be restored and/or verified, easing cleanup + sandbox = sinon.createSandbox(); + + // Create a sinon stub (object) for the authenticate middleware + authenticateStub = sandbox.stub(authController, 'authenticate'); + + // Mock res.locals.username and res.locals.id to be the values of testAccount + authenticateStub.callsFake((req, res, next) => { + res.locals.username = testAccount.username; + res.locals.id = testAccount.id; + res.cookie('ssid', 'test token', { httpOnly: true }); + next(); + }); + + // Use the mock middleware by replacing the original middleware in the middleware chain + // server.use(authController.authenticate); + + // create the app AFTER stubbing authenticate middleware (so the stub is made before a reference to authController.authenticate is set when creating app) + server = require('../../server/server'); + console.log('sandbox before each', sandbox); + console.log('authenticateStub before each', authenticateStub); +}); + +afterEach(() => { + // Restore the original middleware function + // authenticateStub.restore(); + sandbox.restore(); + // console.log('sandbox AFTER each', sandbox); + console.log('from the after each'); +}); + +describe('/projects projectRouter', () => { + const testProject = { + project_name: 'Test Project', + projectObject: { state: 'state' }, + projectOwner: 'testflynn5', + }; + + // make a testAccount + const testAccount = { + username: 'testflynn5', + id: '12345678', + project_ids: ['1'], + }; + + // in mock auth middleware, assign res.locals.username and res.locals.id to the username + // and id of testAccount + + // describe('find a project, GET to /find', () => { + // it('responds with 200 status', () => { + // return request(server).get('/projects/find').expect(200); + // }); + + // it('should retrieve all projects from the database', () => {}); + // }); + + describe('saving a project, POST to /saveProject', () => { + it('responds with 201 status', () => { + return request(server) + .post('/projects/saveProject') + .send(testProject) // sending the testProject in req.body + .expect(201); + }); + }); +});