首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嘲弄模仿/监视被链接的猫鼬(查找、排序、限制、跳过)方法

嘲弄模仿/监视被链接的猫鼬(查找、排序、限制、跳过)方法
EN

Stack Overflow用户
提问于 2019-02-06 19:55:02
回答 6查看 3.8K关注 0票数 7

我想做的是:

  • 监视链接到find()上的方法调用,用于静态模型方法定义
    • 链式方法:sort()limit()skip()

样本调用

  • 目标:监视静态模型方法定义中传递给每个方法的参数: ..。静态法def 结果=等待this.find({}).sort({}).limit().skip(); ..。静态法def
  • find()作为args收到了什么:用findSpy完成
  • sort()作为args收到了什么:不完整
  • limit()作为args收到了什么:不完整
  • skip()作为args收到了什么:不完整

我试过的是:

  • mockingoose库,但它仅限于find()
  • 我成功地模拟了find()方法本身,但没有模拟在它之后出现的链式调用( )。
    • const findSpy = jest.spyOn(models.ModelName, 'find');

  • 模拟链式方法调用的研究未获成功
EN

回答 6

Stack Overflow用户

发布于 2019-02-06 21:11:10

我在任何地方都找不到解决办法。这就是我是如何解决这个问题的。如果你知道更好的方法,请告诉我!

为了给出一些上下文,这是我作为一个附带项目正在进行的REST实现的Medium.com API的一部分。

我怎么嘲笑他们

  • 我已经对每个链式方法进行了模拟和设计,以返回模型模拟对象本身,以便它能够访问链中的下一个方法。
  • 链中的最后一个方法(skip)被设计来返回结果。
  • 在测试本身中,我使用Jest mockImplementation()方法为每个测试设计它的行为
  • 所有这些都可以在使用expect(StoryMock.chainedMethod).toBeCalled[With]()时被监视。
代码语言:javascript
复制
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(() => []),
};

待测试的静态方法定义

代码语言:javascript
复制
/**
 * 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 });
}

完整的Jest测试,以查看模拟的实现

代码语言:javascript
复制
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) },
        });
      });
    });
  });
});
票数 3
EN

Stack Overflow用户

发布于 2021-09-07 07:24:33

代码语言:javascript
复制
jest.spyOn(Post, "find").mockImplementationOnce(() => ({
    sort: () => ({
        limit: () => [{
            id: '613712f7b7025984b080cea9',
            text: 'Sample text'
        }],
    }),
}));

票数 1
EN

Stack Overflow用户

发布于 2019-11-21 01:58:20

下面是我如何用sinonjs做这个呼叫:

代码语言:javascript
复制
 await MyMongooseSchema.find(q).skip(n).limit(m)

这可能会给你提供一些线索,让你对Jest这样做:

代码语言:javascript
复制
sinon.stub(MyMongooseSchema, 'find').returns(
    {
        skip: (n) => {
            return {
                limit: (m) => {
                    return new Promise((
                        resolve, reject) => {
                            resolve(searchResults);
                        });
                }   
            }
        }
    });


sinon.stub(MyMongooseSchema, 'count').resolves(searchResults.length);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54561550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档