我花了一整天的时间来寻找这个。我有以下代码。
// CarModel.js
const makeModel = require('./makeModel');
const connectDB = require('../db/connection');
const { dbName, carCollection } = require('../../config');
module.exports = makeModel({ buildDb: connectDB(dbName), collectionName: carCollection });
// carHandler.js
const CarService = require('../services/CarService');
const carModel = require('../models/CarModel');
module.exports.list = async (event) => {
// set to empty object if the value is null
const queryParams = event.queryStringParameters || {};
// setting default of page and perPage
const { page = 1, perPage = 10} = queryParams;
const carService = CarService({ carModel });
const response = await carService.getPaginatedData({ page, perPage });
return response;
}
在我的测试中,我想模拟 CarModel
或 CarService
。要么对我有用。我嘲笑这些的原因是用内存数据库替换真实数据库。但我找不到任何可行的解决方案。如果你们有任何想法,我将不胜感激。
const { list } = require('../carHandler');
const CarService = require('../../services/CarService');
const connectDB = require('../fixture/db/connection');
const makeModel = require('../../models/makeModel');
it('Paginated data is returned when no query parameters are passed', async () => {
const event = {
queryStringParameters: {},
requestContext: {
path: 'car'
}
};
const db = await connectDB();
// Try 1:
// tried this..not working
const fakeCarModel = makeModel({buildDb: db, collectionName: 'cars'});
jest.mock('../../models/CarModel', () => fakeCarModel);
// Try 2:
// this one didn't work as well
const mockCarService = CarService({ carModel: fakeCarModel});
jest.mock('../../services/CarService', () => mockCarService);
const response = await list(event);
const body = JSON.parse(response);
expect(body).toHaveProperty('data');
expect(body).toHaveProperty('paginator');
});
###EDIT###
CarService.js
module.exports = function CarService({ carModel }) {
async function create(data) {
return await carModel.insertOne({ someKey: someValue });
}
async function getPaginatedData({page = 1, perPage = 10, sortBy = 'updated_at', sortMethod = 'DESC'}) {
// build aggregate query
return await carModel.aggregate(someAggregateQuery)
}
return {
create,
getPaginatedData
};
}