Skip to content

Commit

Permalink
add tests, refactor bin files
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcel Kalveram committed May 5, 2019
1 parent de1b670 commit dcf7ea5
Show file tree
Hide file tree
Showing 8 changed files with 126 additions and 77 deletions.
25 changes: 25 additions & 0 deletions bin/bootstrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const mongoose = require("mongoose")
const dotenv = require("dotenv")

/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
dotenv.load({ path: ".env" })

const connectToMongo = cb => {
mongoose.Promise = global.Promise
mongoose
.connect(process.env.MONGODB_URI || "mongodb://localhost:27017/vlctechhub", {
user: process.env.MONGODB_USER,
pass: process.env.MONGODB_PASS,
})
.then(cb, err => {
console.error(err)
console.log("%s MongoDB connection error. Please make sure MongoDB is running.", chalk.red("✗"))
process.exit()
})
}

module.exports = {
connectToMongo,
}
36 changes: 6 additions & 30 deletions bin/send-notifications.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,9 @@
#!/usr/bin/env node

const mongoose = require("mongoose");
const dotenv = require("dotenv");
const notificationsController = require("../controllers/notifications");
const bootstrap = require("./bootstrap")
const notificationsController = require("../controllers/notifications")

/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
dotenv.load({ path: ".env" });

/**
* Connect to MongoDB.
*/
mongoose.Promise = global.Promise;
mongoose.connect(
process.env.MONGODB_URI || "mongodb://localhost:27017/vlctechhub",
{
user: process.env.MONGODB_USER,
pass: process.env.MONGODB_PASS
}
);
mongoose.connection.on("error", err => {
console.error(err);
console.log(
"%s MongoDB connection error. Please make sure MongoDB is running.",
chalk.red("✗")
);
process.exit();
});

notificationsController.sendPushNotificationsForType("events");
notificationsController.sendPushNotificationsForType("jobs");
bootstrap.connectToMongo(() => {
notificationsController.sendPushNotificationsForType("events")
notificationsController.sendPushNotificationsForType("jobs")
})
24 changes: 3 additions & 21 deletions bin/send-reminders.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,8 @@
#!/usr/bin/env node

const mongoose = require("mongoose")
const dotenv = require("dotenv")
const bootstrap = require("./bootstrap")
const remindersController = require("../controllers/reminders")

/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
dotenv.load({ path: ".env" })

/**
* Connect to MongoDB.
*/
mongoose.Promise = global.Promise
mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost:27017/vlctechhub", {
user: process.env.MONGODB_USER,
pass: process.env.MONGODB_PASS,
})
mongoose.connection.on("error", err => {
console.error(err)
console.log("%s MongoDB connection error. Please make sure MongoDB is running.", chalk.red("✗"))
process.exit()
bootstrap.connectToMongo(() => {
remindersController.sendRemindersForEventsOnDate(new Date())
})

remindersController.sendRemindersForEventsOnDate(new Date())
29 changes: 16 additions & 13 deletions controllers/notifications.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,23 @@ const notificationTitles = {
jobs: "Hay una nueva oferta de trabajo",
}

const sendPushNotificationsForType = type => {
remoteApi.fetchLatestItemForType(type).then(latestItem => {
User.getUsersByType(type, latestItem.id).then(users => {
const tokens = users.map(user => user.token)
pushNotificationsHelper.sendNotifications(tokens, {
title: notificationTitles[type],
message:
type === "events"
? latestItem.title
: `${latestItem.title} en ${latestItem.company.name}`,
})
User.setLatestItemIdForUser(tokens, type, latestItem.id).then(res => res)
})
const sendPushNotificationsForType = type =>
remoteApi
.fetchLatestItemForType(type)
.then(latestItem => sendPushNotificationsForLatestItem(type, latestItem))

const sendPushNotificationsForLatestItem = (type, latestItem) =>
User.getUsersByType(type, latestItem.id).then(users =>
sendPushNotificationsToUsers(type, latestItem, users),
)

const sendPushNotificationsToUsers = (type, latestItem, users) => {
const tokens = users.map(user => user.token)
pushNotificationsHelper.sendNotifications(tokens, {
title: notificationTitles[type],
message: type === "events" ? latestItem.title : `${latestItem.title} en ${latestItem.company.name}`,
})
User.setLatestItemIdForUser(tokens, type, latestItem.id).then(res => res)
}

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"license": "MIT",
"scripts": {
"start": "node app.js",
"test": "mocha --reporter spec",
"test": "mocha --reporter spec ./test/**/*",
"postinstall": "npm rebuild node-sass"
},
"dependencies": {
Expand Down
49 changes: 49 additions & 0 deletions test/controllers/notifications.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const { expect } = require("chai")
const sinon = require("sinon")

const notificationsController = require("../../controllers/notifications")
const remoteApi = require("../../services/remoteApi")
const pushNotificationsHelper = require("../../services/pushNotifications")
const User = require("../../models/User")

describe("Test send reminders functions", () => {
let remoteApiStub
let userStub
let pushSpy
before(() => {
remoteApiStub = sinon
.stub(remoteApi, "fetchLatestItemForType")
.resolves({ id: "123", title: "Latest job offer", company: { name: "Apple" } })
userStub = sinon.stub(User, "getUsersByType").resolves([{ token: "abc" }, { token: "def" }])
pushSpy = sinon.spy(pushNotificationsHelper, "sendNotifications")
})
after(() => {
remoteApiStub.restore()
userStub.restore()
pushSpy.restore()
})
afterEach(() => {
pushSpy.resetHistory()
})
it("should test the notifications for jobs", done => {
notificationsController.sendPushNotificationsForType("jobs")
setTimeout(function() {
expect(pushSpy.called).to.eq(true)
expect(pushSpy.firstCall.args[0]).to.eql(["abc", "def"])
expect(pushSpy.firstCall.args[1].title).to.eql("Hay una nueva oferta de trabajo")
expect(pushSpy.firstCall.args[1].message).to.eql("Latest job offer en Apple")
done()
}, 100)
})
it("should test the notifications for events", done => {
remoteApiStub.resolves({ id: "123", title: "ValenciaJS" })
notificationsController.sendPushNotificationsForType("events")
setTimeout(function() {
expect(pushSpy.called).to.eq(true)
expect(pushSpy.firstCall.args[0]).to.eql(["abc", "def"])
expect(pushSpy.firstCall.args[1].title).to.eql("Hay un nuevo evento")
expect(pushSpy.firstCall.args[1].message).to.eql("ValenciaJS")
done()
}, 100)
})
})
30 changes: 19 additions & 11 deletions test/controllers/reminders.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,26 @@ const remoteApi = require("../../services/remoteApi")
const pushNotificationsHelper = require("../../services/pushNotifications")
const User = require("../../models/User")

sinon
.stub(remoteApi, "fetchEventsByDate")
.resolves([
{ date: "2019-05-03T16:00:00Z", title: "test-1" },
{ date: "2019-05-03T16:00:00Z", title: "test-2" },
{ date: "2019-06-03T16:00:00Z", title: "test-3" },
])

sinon.stub(User, "getUsersByEventId").resolves([{ token: "abc" }, { token: "def" }])
const pushSpy = sinon.spy(pushNotificationsHelper, "sendNotifications")

describe("Test send reminders functions", () => {
let remoteApiStub
let userStub
let pushSpy
before(() => {
remoteApiStub = sinon
.stub(remoteApi, "fetchEventsByDate")
.resolves([
{ date: "2019-05-03T16:00:00Z", title: "test-1" },
{ date: "2019-05-03T16:00:00Z", title: "test-2" },
{ date: "2019-06-03T16:00:00Z", title: "test-3" },
])

userStub = sinon.stub(User, "getUsersByEventId").resolves([{ token: "abc" }, { token: "def" }])
pushSpy = sinon.spy(pushNotificationsHelper, "sendNotifications")
})
after(() => {
remoteApiStub.restore()
userStub.restore()
})
it("should test the reminders for events date function", done => {
remindersController.sendRemindersForEventsOnDate("2019-05-03")
setTimeout(function() {
Expand Down
8 changes: 7 additions & 1 deletion test/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@ const user4 = {
}

describe("User Model", () => {
const UserMock = sinon.mock(User)
let UserMock
before(() => {
UserMock = sinon.mock(User)
})
after(() => {
UserMock.restore()
})
it("should return a user by type and token", done => {
UserMock.expects("findOne")
.withArgs({ type: "events", token: "123" })
Expand Down

0 comments on commit dcf7ea5

Please sign in to comment.