ASP.Net Core React spa 集成测试

ASP.Net Core React spa integration test

Asp.Net 核心集成测试看起来很简单,但就我的生活而言,我无法使用我的 React 开发服务器测试入门应用程序。它在浏览器中运行良好,所以我假设 node、npm 和 react 设置正确但不是在 xUnit 下。它失败并出现以下异常:

System.AggregateException:出现一个或多个错误。 ---> System.AggregateException: 发生一个或多个错误。 ---> System.InvalidOperationException: 无法启动 'npm'。要解决此问题:.

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

确保可执行文件在这些目录之一中,或者更新您的 PATH。

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

我认为这是因为它找不到我的 spa 的内容根目录,所以我尝试添加到我的网络主机构建器但没有成功:

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

这是我的测试class:

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 );
    }

我错过了什么?

我的诀窍是将开发环境变量设置为指向 packages.json 文件所在的目录。

以下是我的 xUnit 集成测试的构造函数的摘录 class。

注意,它首先确定解决方案目录(使用GetExecutingAssembly().Location),然后指向web源项目文件夹。 (在我们的环境中,Client.React 是包含 packages.json 文件的解决方案目录下的一个目录)。

然后,使用 Directory.SetCurrentDirectory 设置目录,然后使用 UseWebRoot 设置测试服务器,再次指向 packages.json 文件所在的目录。

Startup 是 ASP.NET 网络启动 class。

    /// <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();

    }