嘲笑/监视猫鼬链接(查找,排序,限制,跳过)方法

时间:2019-02-06 19:55:03

标签: unit-testing mongoose mocking jestjs chained

我要做什么:

  • 监视在静态Model方法定义中使用的链接到find()的方法调用
    • 链接方法:sort()limit()skip()

呼叫示例

  • 目标:在静态Model方法定义中监视传递给每个方法的参数:

    ...静态方法def

    const结果=等待this.find({})。sort({})。limit()。skip();

    ...静态方法def

  • find()作为参数收到了什么:用findSpy

  • 完成
  • sort()作为参数收到了什么:不完整
  • limit()作为参数收到了什么:不完整
  • skip()作为参数收到了什么:不完整

我尝试过的事情:

  • mockingoose库,但仅限于find()
  • 我已经能够成功模拟find()方法本身,但是无法模拟其后的链接调用
    • const findSpy = jest.spyOn(models.ModelName, 'find');
  • 研究模拟链式方法调用未成功

3 个答案:

答案 0 :(得分:0)

我在任何地方都找不到解决方案。这就是我最终解决此问题的方法。 YMMV,如果您知道更好的方法,请告诉我!

为了提供一些背景信息,这是我作为副项目进行的REST implementation of the Medium.com API的一部分。

我如何嘲笑他们

  • 我模拟了每个链接方法,并设计为返回Model模拟对象本身,以便它可以访问链中的下一个方法。
  • 链中(跳过)的最后一个方法旨在返回结果。
  • 在测试本身中,我使用Jest mockImplementation()方法来设计每个测试的行为
  • 然后可以使用expect(StoryMock.chainedMethod).toBeCalled[With]()监视所有这些内容
const StoryMock = {
  getLatestStories, // to be tested
  addPagination: jest.fn(), // already tested, can mock
  find: jest.fn(() => StoryMock),
  sort: jest.fn(() => StoryMock),
  limit: jest.fn(() => StoryMock),
  skip: jest.fn(() => []),
};

要测试的静态方法定义

/**
 * Gets the latest published stories
 * - uses limit, currentPage pagination
 * - sorted by descending order of publish date
 * @param {object} paginationQuery pagination query string params
 * @param {number} paginationQuery.limit [10] pagination limit
 * @param {number} paginationQuery.currentPage [0] pagination current page
 * @returns {object} { stories, pagination } paginated output using Story.addPagination
 */
async function getLatestStories(paginationQuery) {
  const { limit = 10, currentPage = 0 } = paginationQuery;

  // limit to max of 20 results per page
  const limitBy = Math.min(limit, 20);
  const skipBy = limitBy * currentPage;

  const latestStories = await this
    .find({ published: true, parent: null }) // only published stories
    .sort({ publishedAt: -1 }) // publish date descending
    .limit(limitBy)
    .skip(skipBy);

  const stories = await Promise.all(latestStories.map(story => story.toResponseShape()));

  return this.addPagination({ output: { stories }, limit: limitBy, currentPage });
}

全开玩笑测试以查看模拟的实现

const { mocks } = require('../../../../test-utils');
const { getLatestStories } = require('../story-static-queries');

const StoryMock = {
  getLatestStories, // to be tested
  addPagination: jest.fn(), // already tested, can mock
  find: jest.fn(() => StoryMock),
  sort: jest.fn(() => StoryMock),
  limit: jest.fn(() => StoryMock),
  skip: jest.fn(() => []),
};

const storyInstanceMock = (options) => Object.assign(
  mocks.storyMock({ ...options }),
  { toResponseShape() { return this; } }, // already tested, can mock
); 

describe('Story static query methods', () => {
  describe('getLatestStories(): gets the latest published stories', () => {
    const stories = Array(20).fill().map(() => storyInstanceMock({}));

    describe('no query pagination params: uses default values for limit and currentPage', () => {
      const defaultLimit = 10;
      const defaultCurrentPage = 0;
      const expectedStories = stories.slice(0, defaultLimit);

      // define the return value at end of query chain
      StoryMock.skip.mockImplementation(() => expectedStories);
      // spy on the Story instance toResponseShape() to ensure it is called
      const storyToResponseShapeSpy = jest.spyOn(stories[0], 'toResponseShape');

      beforeAll(() => StoryMock.getLatestStories({}));
      afterAll(() => jest.clearAllMocks());

      test('calls find() for only published stories: { published: true, parent: null }', () => {
        expect(StoryMock.find).toHaveBeenCalledWith({ published: true, parent: null });
      });

      test('calls sort() to sort in descending publishedAt order: { publishedAt: -1 }', () => {
        expect(StoryMock.sort).toHaveBeenCalledWith({ publishedAt: -1 });
      });

      test(`calls limit() using default limit: ${defaultLimit}`, () => {
        expect(StoryMock.limit).toHaveBeenCalledWith(defaultLimit);
      });

      test(`calls skip() using <default limit * default currentPage>: ${defaultLimit * defaultCurrentPage}`, () => {
        expect(StoryMock.skip).toHaveBeenCalledWith(defaultLimit * defaultCurrentPage);
      });

      test('calls toResponseShape() on each Story instance found', () => {
        expect(storyToResponseShapeSpy).toHaveBeenCalled();
      });

      test(`calls static addPagination() method with the first ${defaultLimit} stories result: { output: { stories }, limit: ${defaultLimit}, currentPage: ${defaultCurrentPage} }`, () => {
        expect(StoryMock.addPagination).toHaveBeenCalledWith({
          output: { stories: expectedStories },
          limit: defaultLimit,
          currentPage: defaultCurrentPage,
        });
      });
    });

    describe('with query pagination params', () => {
      afterEach(() => jest.clearAllMocks());

      test('executes the previously tested behavior using query param values: { limit: 5, currentPage: 2 }', async () => {
        const limit = 5;
        const currentPage = 2;
        const storyToResponseShapeSpy = jest.spyOn(stories[0], 'toResponseShape');
        const expectedStories = stories.slice(0, limit);

        StoryMock.skip.mockImplementation(() => expectedStories);

        await StoryMock.getLatestStories({ limit, currentPage });
        expect(StoryMock.find).toHaveBeenCalledWith({ published: true, parent: null });
        expect(StoryMock.sort).toHaveBeenCalledWith({ publishedAt: -1 });
        expect(StoryMock.limit).toHaveBeenCalledWith(limit);
        expect(StoryMock.skip).toHaveBeenCalledWith(limit * currentPage);
        expect(storyToResponseShapeSpy).toHaveBeenCalled();
        expect(StoryMock.addPagination).toHaveBeenCalledWith({
          limit,
          currentPage,
          output: { stories: expectedStories },
        });
      });

      test('limit value of 500 passed: enforces maximum value of 20 instead', async () => {
        const limit = 500;
        const maxLimit = 20;
        const currentPage = 2;
        StoryMock.skip.mockImplementation(() => stories.slice(0, maxLimit));

        await StoryMock.getLatestStories({ limit, currentPage });
        expect(StoryMock.limit).toHaveBeenCalledWith(maxLimit);
        expect(StoryMock.addPagination).toHaveBeenCalledWith({
          limit: maxLimit,
          currentPage,
          output: { stories: stories.slice(0, maxLimit) },
        });
      });
    });
  });
});

答案 1 :(得分:0)

这是我使用sinonjs进行通话的方式:

 await MyMongooseSchema.find(q).skip(n).limit(m)

使用Jest可能会为您提供线索:

sinon.stub(MyMongooseSchema, 'find').returns(
    {
        skip: (n) => {
            return {
                limit: (m) => {
                    return new Promise((
                        resolve, reject) => {
                            resolve(searchResults);
                        });
                }   
            }
        }
    });


sinon.stub(MyMongooseSchema, 'count').resolves(searchResults.length);

答案 2 :(得分:0)

这对我有用:

jest.mock("../../models", () => ({
     Action: {
         find: jest.fn(),
     },
}));

Action.find.mockReturnValueOnce({
    readConcern: jest.fn().mockResolvedValueOnce([
        { name: "Action Name" },
    ]),
});