How to use User.findOne method in ava

Best JavaScript code snippet using ava

user.spec.js

Source:user.spec.js Github

copy

Full Screen

1"use strict";2const request = require("supertest");3const expect = require("chai").expect;4const sinon = require("sinon");5const mockDB = require("../mockdata/database");6const app = require("../testhelper").app;7const User = require("../../models/user");8const TokenGenerator = require("../../services/TokenGenerator");9describe("UserController", () => {10 before(() => {11 sinon.stub(User, "findAllNotActive", () => {12 return Promise.resolve(mockDB.users);13 });14 sinon.stub(User, "saveOne", (reqbody) => {15 return Promise.resolve(mockDB.users[0]);16 });17 sinon.stub(User, "findOne", () => {18 return Promise.resolve(mockDB.users[0]);19 });20 sinon.stub(User, "update", () => {21 return Promise.resolve([1]);22 });23 });24 after(() => {25 User.findAllNotActive.restore();26 User.saveOne.restore();27 User.findOne.restore();28 User.update.restore();29 });30 describe("POST /user (saveOne)", () => {31 it("should save user and return it", (done) => {32 request(app)33 .post("/user")34 .send({ name: "user to be saved" })35 .set("Accept", "application/json")36 .expect("Content-Type", /json/)37 .expect(200, { message: "User was successfully saved" }, done);38 });39 it("should fail with 500 if saveone throws error", (done) => {40 User.saveOne.restore();41 sinon.stub(User, "saveOne", () => {42 return Promise.reject();43 });44 request(app)45 .post("/user")46 .set("Accept", "application/json")47 .expect(500, { message: "User saveOne produced an error" }, done);48 });49 });50 describe("GET /user", () => {51 it("findOne should call User-model correctly and return correct user", (done) => {52 request(app)53 .get("/user/1")54 .set("Accept", "application/json")55 .expect("Content-Type", /json/)56 .expect(200, mockDB.users[0], done);57 });58 it("should fail with 500 if findAllNotActive throws error", (done) => {59 User.findOne.restore();60 sinon.stub(User, "findOne", () => {61 return Promise.reject();62 });63 request(app)64 .get("/user/1")65 .set("Accept", "application/json")66 .expect(500, { message: "User findOne produced an error" }, done);67 });68 it("findAllNotActive should call User-model correctly and return all users", (done) => {69 request(app)70 .get("/user")71 .set("Accept", "application/json")72 .expect("Content-Type", /json/)73 .expect(200, mockDB.users, done);74 });75 it("should fail with 500 if findAllNotActive throws error", (done) => {76 User.findAllNotActive.restore();77 sinon.stub(User, "findAllNotActive", () => {78 return Promise.reject();79 });80 request(app)81 .get("/user")82 .set("Accept", "application/json")83 .expect(500, { message: "User findAllNotActive produced an error" }, done);84 });85 });86 describe("PUT /user/:id", () => {87 it("should call User-model and update one User correctly", (done) => {88 request(app)89 .put("/user/1")90 .set("Accept", "application/json")91 .expect("Content-Type", /json/)92 .expect(200, done);93 });94 it("should fail miserably with 500 if update throws error", (done) => {95 User.update.restore();96 sinon.stub(User, "update", () => {97 return Promise.reject();98 });99 request(app)100 .put("/user/1")101 .set("Accept", "application/json")102 .expect("Content-Type", /json/)103 .expect(500, done);104 });105 });106 describe("POST /login", () => {107 it("should find correct user and create a token", (done) => {108 User.findOne.restore();109 sinon.stub(User, "findOne", () => {110 return Promise.resolve(mockDB.users[0]);111 });112 var generateTokenSpy = sinon.spy(TokenGenerator, "generateToken");113 request(app)114 .post("/login")115 .send(mockDB.users[0])116 .set("Accept", "application/json")117 .expect("Content-Type", /json/)118 .expect(res => {119 expect(generateTokenSpy.calledWith(mockDB.users[0])).to.equal(true);120 })121 .expect(200, done);122 });123 it("should fail with 401 if user is not found", (done) => {124 User.findOne.restore();125 sinon.stub(User, "findOne", () => {126 return Promise.resolve(null);127 });128 request(app)129 .post("/login")130 .set("Accept", "application/json")131 .expect(401, { message: "Logging in failed authentication", error: "" }, done);132 });133 it("should fail with 401 if user is not activated", (done) => {134 User.findOne.restore();135 sinon.stub(User, "findOne", () => {136 return Promise.resolve(mockDB.users[1]);137 });138 request(app)139 .post("/login")140 .set("Accept", "application/json")141 .expect(401, { message: "Your account is inactive, please contact admin for activation", error: "" }, done);142 });143 it("should fail with 500 if findOne throws error", (done) => {144 User.findOne.restore();145 sinon.stub(User, "findOne", () => {146 return Promise.reject();147 });148 request(app)149 .post("/login")150 .set("Accept", "application/json")151 .expect(500, { message: "User loginUser produced an error" }, done);152 });153 });...

Full Screen

Full Screen

user.controller.js

Source:user.controller.js Github

copy

Full Screen

2exports.getInfo = async (req, res) => {3 var requested = req.query.requested;4 var requester = req.query.requester;5 console.log("querying " + requested);6 result = await User.findOne({name:requested});7 isFriend = result.friends.includes(requester) ? true : false;8 delete result.phone9 requestedResult = await User.findOne({name:requested});10 requesterResult = await User.findOne({name:requester});11 mutual = []12 requestedResult.friends.forEach(function(friend){13 if (requesterResult.friends.includes(friend)){14 mutual.push(friend)15 }16 });17 res.json({18 status: 0,19 user: result,20 isFriend: isFriend,21 mutual: mutual22 });23};24exports.getMutualFriends = async (req, res) => {25 var requested = req.query.requested;26 var requester = req.query.requester;27 console.log("querying mutual friend " + requested)28 requestedResult = await User.findOne({name:requested});29 requesterResult = await User.findOne({name:requester});30 mutual = []31 requestedResult.friends.forEach(function(friend){32 if (requesterResult.friends.includes(friend)){33 mutual.push(friend)34 }35 });36 res.json({37 status: 0,38 mutual: mutual39 });40};41exports.create = (req, res) => {42 if(!req.body) {43 return res.status(400).send({44 message: "Note content can not be empty"45 });46 }47 console.log(req.body)48 if(!req.body.facebook) {49 fb = "Not Set";50 } else {51 fb = req.body.facebook;52 }53 if(!req.body.linkedin) {54 li = "Not Set";55 } else {56 li = req.body.linkedin;57 }58 if(!req.body.phone) {59 phone = "";60 } else {61 phone = req.body.phone;62 }63 const user = new User({64 name: req.body.name,65 bio: req.body.bio,66 facebook: fb,67 linkedin: li,68 phone: phone69 });70 user.save(function(err){71 if (err){72 console.log(err);73 } else {74 res.json({status:0});75 }76 });77};78exports.befriend = (req, res) => {79 if(!req.query) {80 return res.status(400).send({81 message: "Note content can not be empty"82 });83 }84 User.findOne({"name": req.query.requester},"friends",function(err,requester){85 if (err) return handleError(err);86 requester.friends.push(req.query.requested);87 requester.save(function(err){88 if (err){89 console.log(err);90 } else {91 92 }93 });94 });95 User.findOne({"name": req.query.requested},"friends",function(err,requested){96 if (err) return handleError(err);97 requested.friends.push(req.query.requester);98 requested.save(function(err){99 if (err){100 console.log(err);101 } else {102 res.json({status:0});103 }104 });105 });106}107exports.delete = (req, res) => {108 if(!req.body) {109 return res.status(400).send({110 message: "Note content can not be empty"111 });112 }113 // User.findOne({"name":req.query.name},function(err,test){114 // console.log(test.name);115 // });116 User.findOne({"name":req.body.name},function(err,model){117 model.remove(function(err){});118 });119 User.find({},function(err,users){120 users.forEach(function(u){121 idx = u.friends.indexOf(req.body.name)122 if (idx != -1) {123 u.friends.splice(idx,1);124 }125 u.save()126 });127 res.json({status:0})128 });129};130exports.addPics = async (req, res) => {131 var name = req.body.name;132 var pics = req.body.pics;133 result = await User.findOne({name:name});134 result.pics = result.pics.concat(pics);135 result.save(function(err){136 if (err){137 console.log(err);138 } else {139 res.json({status:0});140 }141 });142}143exports.test = async (req, res) => {144 console.log("test")145 res.json({status:0});...

Full Screen

Full Screen

users.js

Source:users.js Github

copy

Full Screen

...12router.post('/login', async (ctx) => {13 try {14 const { userName, userPwd } = ctx.request.body15 // 这里可以 指定返回的字段 三种方式16 // 1. const res = await User.findOne({ userName, userPwd }, 'roleList')17 // 1. const res = await User.findOne({ userName, userPwd }, 'userId userName userEmail state role deptId roleList ')18 // 2. {userId:1, _id:0} 为1的返回 为0的不返回19 // 2. const res = await User.findOne({ userName, userPwd }, {userId:1, _id:0}) // User.findOne 查找账号密码20 // 3. select('userId')21 // 3. const res = await User.findOne({ userName, userPwd }).select('userId') // User.findOne 查找账号密码22 const res = await User.findOne({ userName, userPwd }, 'userId userName userEmail state role deptId roleList') // User.findOne 查找账号密码23 const data = res._doc24 const token = jwt.sign({ // jwt验证25 data: data26 }, 'Jason', { expiresIn: '1h' }); // jwt验证 -- token失效时间27 if (res) {28 data.token = token // jwt验证29 ctx.body = utils.success(res)30 } else {31 ctx.body = utils.fail('用户名或者密码不正确')32 }33 } catch (error) {34 ctx.body = utils.fail(error.msg)35 }36},...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ava automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful