![](/img/trans.png)
[英]Testing typescript code with namespaces by jest (ts-jest)
[英]Testing to see if a function is called with Jest and Typescript, and ts-jest?
所以我正在尝试测试这段代码
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。 如果没有明确的 mocking 发表评论 function,我该如何实现这一点?
谢谢: :)
因此,如果我的代码正确,那么您目前是 mocking,您的CommentHelper
的默认导出为 function。
访问postComment
时,您将获得当前未定义的模拟返回的响应。
正如我在您在示例测试用例中提供的其他内容中看到的那样,您想要测试是否调用了GitAPI
。 在这种情况下,您不能模拟 CommentHelper,因为那时GitApi
被调用。
如果你想模拟CommentHelper
你必须返回
jest.mock('../helpers/CommentHelper', () => {
return {
default: jest.fn().mockImplementation(() => ({
postComment:jest.fn()
}))
};
});
如果你只是想监视GitAPI
你对 go 有好处。 如果您不想调用GitAPI
,请在.mockImplementation
之后添加spyOn
。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.