这是我在没有任何 Cypress 库的情况下如何做到的:
在测试文件的tearDownClass 方法中(在所有测试之后),我添加了这段代码,将window.__coverage__ 保存到.nyc_output/out.json 文件中:
@classmethod
def tearDownClass(cls):
# Put coverage data into file.
data = cls.driver.execute_script('return window.__coverage__')
with open(os.path.join(cls.webAppPath, ".nyc_output", "out.json"), 'w') as outfile:
json.dump(data, outfile)
# Generate HTML coverage report
os.system("cd %s && %s report --reporter=html -e .vue" % (cls.webAppPath, os.path.join(cls.webAppPath, "node_modules", ".bin", "nyc")))
请注意,.nyc_output 文件夹必须位于 Web 应用程序的文件夹中。此外,在测试期间,不应重新加载网页,因为这会重置覆盖计数器,从而提供不正确的覆盖。
但是,这还不够。伊斯坦布尔的代码中有一个错误,所以我使用了一个修复程序,找到了here。在测试之前,我用这种方式修改了istanbul的一部分代码(然后重新编译了web app的代码):
# Fix a bug in istanbul code coverage lib
pathOfFileToModify = os.path.join(webAppPath, "node_modules/istanbul-lib-source-maps/lib/pathutils.js")
with open(pathOfFileToModify, "r") as fileToModify:
modified = fileToModify.read().replace('relativeTo(file, origFile) {\n return', 'relativeTo(file, origFile) {\n if (origFile.indexOf(file) !== -1) { return origFile }\n return')
with open(pathOfFileToModify, "w") as fileToModify: # TODO Maybe figure out how to use read-write mode?
fileToModify.write(modified)
如果有人找到更好的解决方法,请在 cmets 中告诉我。