ASP.Net Core React单页应用程序集成测试

3

Asp.Net Core集成测试似乎很简单,但我却无法使用我的React开发服务器测试起始应用程序。它可以从浏览器中正常运行,因此我认为Node、npm和React已经正确设置,但在xUnit下不行。它会出现以下异常:

System.AggregateException: 发生了一个或多个错误。---> System.AggregateException: 发生了一个或多个错误。---> System.InvalidOperationException: 启动“npm”失败。要解决这个问题:

[1] 确保“npm”已安装并且可以在PATH目录之一找到。 当前的PATH环境变量是:{PATH}

确保可执行文件位于其中一个目录中,或更新您的PATH。

[2] 有关原因的详细信息,请参见InnerException。---> System.ComponentModel.Win32Exception:目录名称无效 ...

我猜这是因为它找不到我的SPA的内容根目录,所以我尝试将其添加到Web主机构建器中,但没有成功:

.UseSolutionRelativeContentRoot( "Solution Relative Path to My App" ) );

这是我的测试类:
public class SampleDataControllerTest
{

    private readonly TestServer server;
    private readonly HttpClient client;

    public SampleDataControllerTest()
    {
        server = new TestServer( WebHost.CreateDefaultBuilder()
            .UseStartup<Startup>()
            .UseSolutionRelativeContentRoot( "Solution Relative Path to My App" ) );
            .UseEnvironment( "Development" );
        client = server.CreateClient();
    }

    [Fact]
    public async Task RootTest()
    {
        HttpResponseMessage page = await client.GetAsync( "/" );
        Assert.NotNull( page );
        Assert.Equal( HttpStatusCode.OK, page.StatusCode );
    }

我漏掉了什么?

1个回答

4
对我来说,关键在于将开发环境变量设置为指向 packages.json 文件所在目录。
以下是我的 xUnit 集成测试类构造函数的一部分。
请注意,它首先确定解决方案目录(使用 GetExecutingAssembly().Location),然后指向 Web 源项目文件夹。在我们的环境中,Client.React 是解决方案目录下包含 packages.json 文件的目录。
然后,使用 Directory.SetCurrentDirectory 设置目录,随后使用 UseWebRoot 设置测试服务器,再次指向 packages.json 文件所在目录。 Startup 是 ASP.NET Web 启动类。
    /// <summary>
    /// Constructor
    /// </summary>
    public IntegrationTest() : base()
    {
        var testAssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        // Remove the "\\bin\\Debug\\netcoreapp2.1"
        var solutionPath = Directory.GetParent(testAssemblyPath.Substring(0, testAssemblyPath.LastIndexOf(@"\bin\", StringComparison.Ordinal))).FullName;
        var clientReactPath = Path.Join(solutionPath, "Client.React");

        // Important to ensure that npm loads and is pointing to correct directory
        Directory.SetCurrentDirectory(clientReactPath);

        var server = new TestServer(new WebHostBuilder()
            .UseEnvironment("Development")
            .UseWebRoot(clientReactPath)
            .UseStartup<Startup>());

        _client = server.CreateClient();

    }

在我的集成测试项目中遇到了这个问题。这个解决方案救了我。 - Dan Cook

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