【问题标题】:Testing to see if a function is called with Jest and Typescript, and ts-jest?测试是否使用 Jest 和 Typescript 以及 ts-jest 调用函数?
【发布时间】:2020-06-19 21:58:16
【问题描述】:

所以我正在尝试测试这段代码

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

这是错误:

    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 函数的情况下实现这一点?

谢谢! :)

【问题讨论】:

    标签: javascript node.js typescript jestjs ts-jest


    【解决方案1】:

    因此,如果我的代码正确,则您当前正在模拟将 CommentHelper 的默认导出作为函数。

    访问postComment 时,您将获得当前未定义的模拟返回的响应。

    正如我在您在示例测试用例中提供的其他内容中看到的那样,您想要测试是否调用了 GitAPI。在这种情况下,您不能模拟 CommentHelper,因为这样就不可能调用 GitApi

    如果你想模拟CommentHelper你必须返回

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

    如果你只是想监视GitAPI,那你就去吧。如果您不希望 GitAPI 被调用,请在您的 spyOn 之后添加 .mockImplementation

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2020-03-31
      • 2021-11-27
      • 2019-03-14
      相关资源
      最近更新 更多