Visual Studio 2019测试资源管理器中的Jest单元测试

5

我使用 dotnet new react 创建了一个新的ASP.NET Core React应用程序。然后我添加了一些Jest单元测试,当我在命令行上运行 npm test 时,测试可以很好地运行。

我想能够从Visual Studio 2019中运行这些测试,无论是使用Test Explorer窗口还是ReSharper。

首先,似乎ReSharper只支持Jasmine而不是Jest(ReSharper文档功能请求)。

因此,我尝试使用Test Explorer,遵循官方指南。它支持Jest。但是,ASP.NET Core的React模板不是一个node.js项目,因此测试框架和其他选项都不可用。因此,Test Explorer找不到任何测试。

然后我尝试使用命令 vstest.console.exe MyProject.csproj / TestAdapterPath:“C:\ Program Files(x86)\ Microsoft Visual Studio \ 2019 \ Professional \ Common7 \ IDE \ Extensions \ Microsoft \ NodeJsTools \ TestAdapter” 运行测试。输出结果让我有些希望:

Microsoft (R) Test Execution Command Line Tool Version 16.5.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...

A total of 1 test files matched the specified pattern.
No test is available in MyProject.csproj. Make sure that test 
discoverer & executors are registered and platform & framework version settings are appropriate and 
try again.

测试运行器至少找到了一个测试文件(实际上我有两个),但它不知道应该使用Jest 执行程序。我可以在 .csproj 文件中添加一些内容让它起作用吗?

你有没有找到解决办法? - Vapid
不,我什么也没有。我现在只是使用命令行。 - Koja
1个回答

2
这是我使`.njsproj`工作的方法。我希望能够让`.csproj`也能正常工作。首先创建一个带有TypeScript的空白Node.js控制台应用程序。测试过使用JavaScript也可以正常工作。

enter image description here

创建一个名为 "tests" 的文件夹,并添加一个 JavaScript Jest 单元测试文件:

enter image description here

无法找到“jest”包。必须在项目中本地安装“jest”。可以通过解决方案资源管理器中的 npm 管理器或通过 Node.js 交互窗口使用“.npm install jest --save-dev”命令在本地安装“jest”。无法找到“jest-editor-support”包。必须在项目中本地安装“jest-editor-support”。可以通过解决方案资源管理器中的 npm 管理器或通过 Node.js 交互窗口使用“.npm install jest-editor-support --save-dev”命令在本地安装“jest-editor-support”。
然后从 Visual Studio 2019 的 Developer 命令提示符中运行以下命令:
vstest.console.exe "C:\Users\Oscar\source\repos\NodejsConsoleApp1\NodejsConsoleApp1\NodejsConsoleApp1.njsproj" "/TestAdapterPath:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\Microsoft\NodeJsTools\TestAdapter"

enter image description here

安装了 jestjest-editor-support,依赖类型为 Development

enter image description here

做完这个之后,测试就可以运行了:

enter image description here

现在,这些测试也会出现在测试资源管理器中:

enter image description here

然后将 UnitTest1.js 重命名为 UnitTest1.ts。您应该会看到以下错误:

enter image description here

安装@types/jest作为开发依赖,就应该可以工作了:

enter image description here

我本来不需要说明这个,但如果出现问题,请检查项目属性并设置JavaScript单元测试值。

enter image description here

还要检查测试文件的属性,如果是通过GUI添加的,则这些值应该默认正确。

enter image description here


1
遗憾的是,这不能与 csproj 一起使用,因为它假定 Javascript 的根目录是项目的根目录,即使我将测试适配器的源代码更改为查找正确的位置,也会有很多东西默默地失败。 - Velizar Hristov
1
这在VS 2022中仍然可以工作,但您需要从C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\TestPlatform运行命令,并且TestAdapterPath为C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Extensions\Microsoft\NodeJsTools\TestAdapter - djbyter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接