Как подсмотреть встроенный метод макета с помощью JEST? - PullRequest
0 голосов
/ 14 февраля 2020

Я пытаюсь смоделировать нативный метод mongodb, т.е. найти . но найти есть встроенный метод, такой как count, limit, skip. Мне нужно смоделировать их все, чтобы проверить с tohaveBeenCalledWith (). Я пытался смоделировать методы, но я не смог проверить jest tohaveBeenCalledWith () matcher, так как он thows this.collection.find (...). Limit (...). Skip не является функцией ошибка. Кто-нибудь может мне с этим помочь?

метод для тестирования: sample.ts

export class MongoDb<T> {
 async SampleMethod(
        args1: object,
        limit: number = 25,
        skip: number = 0): Promise<T[]> {
        return this.collection.find(filter).limit(limit).skip(skip).toArray();
    }
}

мой макет выглядит так

const mongoInstance = new MongoDb<TestEntityType>(
        new MongoClient('testClient'),
        {

            find: jest.fn(() => ({                
                count: (_: Promise<number>) => Promise.resolve(10),                
                limit: (num: Promise<number>) => Promise.resolve(num),                
                skip: (num: Promise<number>) => Promise.resolve(num),
                toArray: (_: Promise<TestEntityType[]>) => Promise.resolve([
                    {string_field: 'value'}
                ])
            })),
        } as unknown as Collection
    );

набор тестов

describe('Find', () => {
        const spyFind = jest.spyOn(mongoInstance.collection, 'find');
        const spyLimit = jest.spyOn(mongoInstance.collection, 'limit');
        const spySkip= jest.spyOn(mongoInstance.collection, 'skip');
        // Cleaning
        afterAll(() => {
            spyFind.mockClear();
        });
        it('should exclude fields by default when projection fields are passed', async () => {
            // Preparing
            const filter = {
                field1: '1'
            };
            // Executing
            await mongoInstance.SampleMethod(filter);
            // Verifying
            expect(spyFind).toHaveBeenCalledWith(filter);
            expect(spyLimit).toHaveBeenCalledWith(25);
            expect(spySkip).toHaveBeenCalledWith(0);
        });
    });

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...