我需要测试一些代码,这些代码在分配了 URL 然后单击的文档上创建一个元素。
我正在使用杰斯特。
const link = document.createElement('a')
Run Code Online (Sandbox Code Playgroud)
我放弃了尝试模拟文档,因为我看不到一种简单的方法来做到这一点,尽管模拟点击会很好。
我需要知道createElement发生了什么,所以我决定创建一个间谍:
jest.spyOn(document, 'createElement')
Run Code Online (Sandbox Code Playgroud)
由于某种原因,间谍破坏了测试,我得到了与尝试模拟文档时相同的错误:
const link = document.createElement('a')
Run Code Online (Sandbox Code Playgroud)
下面的代码document.createElement是:
link.href = url
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
这是解决方案,我使用node.js运行环境进行演示:
\n\nclass Link {\n private name: string;\n private _href: string = \'\';\n constructor(name) {\n this.name = name;\n }\n\n get href() {\n return this._href;\n }\n\n set href(url) {\n this._href = url;\n }\n}\n\nconst document = {\n createElement(name) {\n return new Link(name);\n }\n};\n\nfunction createLink(url) {\n const link = document.createElement(\'a\');\n link.href = url;\n return link;\n}\n\nexport { createLink, document, Link };\n\nRun Code Online (Sandbox Code Playgroud)\n\n单元测试:
\n\nimport { createLink, document, Link } from \'./\';\n\ndescribe(\'createLink\', () => {\n it(\'t1\', () => {\n const url = \'https://github.com/mrdulin\';\n jest.spyOn(document, \'createElement\').mockReturnValueOnce(new Link(\'mock link\'));\n const link = createLink(url);\n expect(link).toBeInstanceOf(Link);\n expect(link.href).toBe(url);\n });\n});\n\nRun Code Online (Sandbox Code Playgroud)\n\n PASS src/stackoverflow/57088724/index.spec.ts\n createLink\n \xe2\x9c\x93 t1 (6ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 2.451s, estimated 3s\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
19863 次 |
| 最近记录: |