Проверяете, вызывается ли функция с помощью Jest, Typescript и ts-jest? - PullRequest
0 голосов
/ 17 июня 2020

Итак, я пытаюсь проверить этот код

src / helpers / CommentHelper.ts:

export default class CommentHelper {

    gitApiObject: GitApi.IGitApi ;

    constructor(gitApiObject: GitApi.IGitApi)
    {
        this.gitApiObject = gitApiObject;
    }

    async postComment(commentContent: string, repoId: string, pullRequestId: number): Promise<any> {
        const comment: GitInterfaces.Comment = <GitInterfaces.Comment>{content: commentContent};
        const newCommentThread: GitInterfaces.GitPullRequestCommentThread = <GitInterfaces.GitPullRequestCommentThread>{comments: [comment]}
        await this.gitApiObject.createThread(newCommentThread, repoId, pullRequestId);
    }
}

Вот тесты:

import  CommentHelper  from "../helpers/CommentHelper";
import { mocked } from 'ts-jest/utils';
import  { GitApi, IGitApi }  from "azure-devops-node-api/GitApi";


jest.mock('../helpers/CommentHelper', () => {
    return {
      default: jest.fn().mockImplementation(() => {})
    };
});

describe("CommentHelper Tests",  () => {
    const mockedGitApi = mocked(GitApi, true);

    beforeEach(() => {
        mockedGitApi.mockClear();
    });

    it("Check to see if the gitApiObject is called properly",  () => {
        const commentHelper = new CommentHelper(<any>mockedGitApi);
        const spy = jest.spyOn(GitApi.prototype ,'createThread')
        commentHelper.postComment("", "", 0);
        expect(spy).toHaveBeenCalled();
    })
})

Это error:

    TypeError: commentHelper.postComment is not a function

      23 |         const commentHelper = new CommentHelper(<any>mockedGitApi);
      24 |         const spy = jest.spyOn(GitApi.prototype ,'createThread')
    > 25 |         commentHelper.postComment("", "", 0);
         |                       ^
      26 |         expect(spy).toHaveBeenCalled();
      27 |     })
      28 |

Сейчас мы находимся на ранней стадии проекта, поэтому тесты чрезвычайно просты. Мы просто хотим убедиться, что вызывается gitApiObject / createThread. Как я могу добиться этого без явного имитации функции postComment?

Спасибо! :)

1 Ответ

0 голосов
/ 18 июня 2020

Итак, если я правильно понял ваш код, вы в настоящее время высмеиваете экспорт по умолчанию вашего CommentHelper как функции.

При доступе к postComment вы получите ответ своего макета, который в настоящее время не определен.

Как я вижу в других вещах, которые вы предоставили в своем примере тестового примера, вы хотите проверить, был ли вызван GitAPI. В этом случае вы не можете имитировать CommentHelper, так как тогда нет возможности для вызова GitApi.

Если вы хотите поиздеваться над CommentHelper, вам нужно вернуть

jest.mock('../helpers/CommentHelper', () => {
    return {
      default: jest.fn().mockImplementation(() => ({
        postComment:jest.fn()
      }))
    };
});

, если вы просто хотите шпионить за GitAPI вашим товаром, на go. Если вы не хотите, чтобы GitAPI назывался, добавьте .mockImplementation после spyOn.

Надеюсь, это поможет!

...