Skip to content

Instantly share code, notes, and snippets.

@tehvicke
tehvicke / thought-model.test.js
Created February 14, 2020 09:52
Simple test to ensure data can be created in the database
afterEach(async () => {
Thought.deleteMany({})
})
describe('thought model tests', () => {
it('can create a thought', async () => {
await new Thought({ message: 'test thought' }).save()
const thoughtsCount = await Thought.countDocuments()
expect(thoughtsCount).toEqual(1)
}),
@tehvicke
tehvicke / thought-service.js
Created February 14, 2020 10:08
The exported higher order functions
module.exports = Thought => {
return {
createThought: createThought(Thought),
listThoughts: listThoughts(Thought),
updateLikes: updateLikes(Thought)
}
}
@tehvicke
tehvicke / thought-service.test.js
Created February 14, 2020 10:14
Simple test using sinon in a mock model to listen on whether a function was called or not
describe('updateLike test', () => {
it('should updates the heart count', () => {
const MockModel = {
findOneAndUpdate: sinon.spy()
}
const thoughtService = ThoughtService(MockModel)
thoughtService.updateLikes()
const actual = MockModel.findOneAndUpdate.calledOnce
const expected = true
expect(actual).toEqual(expected)
@tehvicke
tehvicke / thought-model.test.js
Created February 14, 2020 12:22
Test to validate that we can update an object in the database
it('can update likes on a thought', async () => {
const thought = await new Thought({ message: 'test message' }).save()
const fetchedThought = await Thought.findOneAndUpdate(
{ _id: thought._id },
{ $inc: { hearts: 1 } },
{ new: true }
)
expect(fetchedThought.hearts).toEqual(1)
})
@tehvicke
tehvicke / thought-service.js
Created February 14, 2020 12:35
List thought function
const listThoughts = Thought => number => {
return Thought.find({})
.sort({ _id: 'desc' })
.limit(number)
}
@tehvicke
tehvicke / thought-service.test.js
Created February 14, 2020 12:48
Testing a service with mock models and a stub
describe('listThoughts test', () => {
it('should list Thoughts', () => {
/* Mock model to imitate the find function */
const MockModel = {
find: () => {}
}
/* We create a stub to imitate chained methods */
sinon.stub(MockModel, 'find').callsFake(() => {
return {
sort: () => {
@tehvicke
tehvicke / app.test.js
Created February 14, 2020 13:01
Endpoint testing
describe('route testing', () => {
it('can get thoughts', async () => {
await request(server)
.get('/')
.expect(200)
}),
it('can post thoughts', async () => {
await request(server)
.post('/')
.send({ message: 'test message' })