How to run QUnit test and get back test result in C# via JavaScript callback?

前端 未结 2 1384
悲哀的现实
悲哀的现实 2021-02-10 07:27

In my several projects, I use MVC pattern for separating code (of concerns) into 3 tiers. Both of Model and Control tiers run on C# so I use testing framework like MSTest or NUn

2条回答
  •  醉酒成梦
    2021-02-10 07:57

    For cross browser testing, Selenium WebDriver is the best option for solving this problem because we can easily switch between browser by changing only one line of code.

    1. Install Selenium WebDriver package to project via NuGet.

    enter image description here

    2.Download preferred driver to your project, add to your project and set "Copy to Output Directory" equals "Copy if newer". For this example, I use Chrome driver to run Selenium with Google Chrome on my machine.

    3.In test method, create driver and set max execution time before running QUnit.

    var browser = new ChromeDriver();
    var navigator = browser.Navigate();
    
    // Currently, max execution time is one minute.
    browser.Manage().Timeouts()
           .SetScriptTimeout(new TimeSpan(0, 1, 0));
    

    4.Please make sure that you already set autostart of QUnit to false.

    QUnit.config.autostart = false;
    

    5.Navigate to QUnit page. In this case, I use local webpage in solution folder.

     browser.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 1, 0));
    navigator.GoToUrl(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"../../../QUnit example/qunit-demo.htm"));
    

    6.Use ExecuteAsyncScript method in browser object to register callback for QUnit.done function and manually start QUnit testing.

    var response = browser.ExecuteAsyncScript
    (
        "var callback = arguments[arguments.length - 1];" +
        "QUnit.done(callback); QUnit.start();"
    );
    

    7.When QUnit test done, it will return a response. We need to convert it as suitable type and get the test result.

    var testResult = response as Dictionary;
    
    if(testResult == null) throw new Exception("Unhandle error occur while running QUnit."); 
    
    Console.WriteLine("Test complete in " + (long)testResult["runtime"] + " ms.");
    Console.WriteLine("---------------------------");
    Console.WriteLine("total: " + (long)testResult["total"]);
    Console.WriteLine("passed: " + (long)testResult["passed"]);
    Console.WriteLine("failed: " + (long)testResult["failed"]);
    

    8.Don't forget to close browser every time use finish testing.

    browser.Close();
    

    PS. I also provide Visual Studio 2012 solution (source code) for this answer.

    Click here to download

    Update 1

    • Fix bug that sometime QUnit start testing before system register callback to done function.
    • Include local QUnit page.
    • Include IEDriver to download solution. However, this version doesn't support for IE10 on Windows 8. But it work fine on IE8.

提交回复
热议问题