34
loading...
This website collects cookies to deliver better user experience
// sum.js
const add = (a, b) => {
return a + b;
}
module.exports = {
add,
};
// sum.test.js
const { add } = require('./sum');
it('should sum numbers', () => {
expect(add(1, 2)).toBe(3);
}
// models/books.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BooksSchema = new Schema({
title: {
type: String,
trim: true
},
author: {
type: Schema.Types.ObjectId,
ref: 'authors'
},
year: {
type: String,
}
});
module.exports = mongoose.model('books', BooksSchema);
// services/books.js
const Books = require('../models/books');
const fetchBooks = () => Books
.find({})
.populate('author')
.exec();
const fetchBook = id => Books
.findById(id)
.populate('author')
.exec();
const createBook = ({title, author, year}) => {
const book = new Books({
title,
author,
year,
});
return book.save();
}
module.exports = {
fetchBooks,
fetchBook,
createBook,
};
Note: the code above is brutally minimal just to keep the example as lean as possible.
mockingoose
with npm i mockingoose -D
.books.test.js
.const mockingoose = require('mockingoose');
const BooksModel = require('../models/books');
const {
fetchBooks,
fetchBook,
createBook,
} = require('./books');
mockingoose
, and then tell to the mocked model, what it supposed to return, for example if you want to return a list of books:mockingoose(BooksModel).toReturn([
{
title: 'Book 1',
author: {
firstname: 'John',
lastname: 'Doe'
},
year: 2021,
},
{
title: 'Book 2',
author: {
firstname: 'Jane',
lastname: 'Doe'
},
year: 2022,
}
], 'find');
toReturn
function expects two values, the first one is the data you want the model to return, the second one is which operations, like find
, findOne
, update
, etc... and in our case we are going to call the find
one as we need to fetch the list of books.// books.test.js
const mockingoose = require('mockingoose');
const BooksModel = require('../models/books');
const {
fetchBooks,
fetchBook,
createBook,
} = require('./books');
describe('Books service', () => {
describe('fetchBooks', () => {
it ('should return the list of books', async () => {
mockingoose(BooksModel).toReturn([
{
title: 'Book 1',
author: {
firstname: 'John',
lastname: 'Doe'
},
year: 2021,
},
{
title: 'Book 2',
author: {
firstname: 'Jane',
lastname: 'Doe'
},
year: 2022,
}
], 'find');
const results = await fetchBooks();
expect(results[0].title).toBe('Book 1');
});
});
});
describe('fetchBook', () => {
it ('should return a book', async () => {
mockingoose(BooksModel).toReturn(
{
_id: 1,
title: 'Book 1',
author: {
firstname: 'John',
lastname: 'Doe'
},
year: 2021,
}, 'findOne');
const results = await fetchBook(1);
expect(results.title).toBe('test');
});
});
exec
or populate
for example, so you don't need to worry about them.npm run test
, you should see your fist tests running successfully:mockingoose
makes my life much easier, and it works fine on CI/CD as well!