我怎么能用玩笑嘲笑节点模块的构造函数

时间:2020-09-17 23:59:35

标签: unit-testing jestjs github-actions

到目前为止,我一直在学习开玩笑并且做得还可以,但是我想出了一些我不知道该如何解决的东西。我需要模拟@ actions / github模块,我想我以正确的方式模拟了模块的方法:

const githubListCommentsMock = jest.fn().mockReturnValue(
{
  id: 1,
  user: {login: 'github-actions[bot]'},
  body: 'Code quality reports: Mock value'
})
const githubDeleteCommentMock = jest.fn()
const githubCreateCommentMock = jest.fn()
const githubIssuesMock = { listComments: githubListCommentsMock,
    deleteComment: githubDeleteCommentMock,
    createComment: githubCreateCommentMock
  }
const githubContextMock = {repo:'Mocked Repository'}
jest.mock('@actions/github', () => ({
  Github:jest.fn().mockImplementation(() => (
     {issues: githubIssuesMock, context: githubContextMock}))
}))

但是我正在测试的文件上有一段代码,它实例化了github模块,如下所示:

const octokit = new github.GitHub(githubToken)

尝试执行文件时,我的测试失败,出现以下错误:

TypeError: github.GitHub is not a constructor

1 个答案:

答案 0 :(得分:0)

也在学习 Jest 并且遇到了类似的挑战。它与您描述的有点不同(并且与 M Mansour 在评论中提到的 hydrated github 客户端内联)。

List<String> result = new Gson().fromJson(value, List.class);

我确信可能有更简洁的方法来做到这一点。在绕了一圈尝试不同的方法之后,我最终一步一步地走了。断言 getOc​​tokit 已被调用,使用 // Setup stub Octokit to return from getOctokit. const StubOctokit = { search: { code: jest.fn() } } // Setup fake response from call to Octokit.search.code. const fakeResponse = { data: { total_count: 4 } } // Code search should return fakeResponse. StubOctokit.search.code.mockReturnValueOnce(fakeResponse); // getOctokit should return the Octokit stub. github.getOctokit.mockReturnValueOnce(StubOctokit); 将其设置为空对象,使用 mockReturnValueOnce 并从那里开始构建直到获得预期结果。