【问题标题】:ASP.Net Core React spa integration testASP.Net Core React spa 集成测试
【发布时间】:2018-10-24 02:37:43
【问题描述】:

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: 目录名无效 ...

我认为这是因为它找不到我的水疗中心的内容根目录,所以我尝试添加到我的虚拟主机构建器,但没有成功:

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

我错过了什么?

【问题讨论】:

    标签: reactjs asp.net-core integration-testing single-page-application xunit


    【解决方案1】:

    对我来说,诀窍是将开发环境变量设置为指向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();
    
        }
    

    【讨论】:

    • 在我的集成测试项目中遇到了这个问题。这救了我。
    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2019-09-12
    相关资源
    最近更新 更多