繁体   English   中英

Mocking 一个带有 Jest 的 NodeJS 模块

[英]Mocking a NodeJS module with Jest

我花了一整天的时间寻找这个。 我有以下代码。

// 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;
}

在我的测试中,我想模拟CarModelCarService 要么对我有用。 我模拟这些的原因是用内存数据库替换真实数据库。 但我找不到任何可行的解决方案。 如果你们中的任何人有任何想法,那么我将不胜感激。

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');
});

###编辑###

汽车服务.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
    };
}
①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM