QUnit - 使用断言

所有断言都在断言类别中.

此类别提供了一组用于编写测试的断言方法.只记录失败的断言.

Sr .No.方法&说明
1

async()

指示QUnit等待异步操作.

2

deepEqual()

深递归比较,处理基本类型,数组,对象,正则表达式,日期和函数.

3

equal()

非严格比较,大致相当于JUnit的assertEquals.

4

expect()

指定预期在测试中运行的断言数.

5

notDeepEqual()

反向深度递归比较,处理基本类型,数组,对象,正则表达式,日期和函数.

6

notEqual()

非严格比较,检查不平等.

7

notOk()

布尔检查,ok()的反转和CommonJS的assert.ok(),等效于JUnit的assertFalse().如果第一个参数为假,则通过.

8

notPropEqual()

严格比较对象自身的属性,检查不等式.

9

notStrictEqual()

严格比较,检查不平等.

10

ok()

布尔检查,相当于CommonJS的断言.ok()和JUnit的assertTrue().如果第一个参数为真,则通过.

11

propEqual()

对象自身属性的严格类型和值比较.

12

push()

报告自定义断言的结果.

13

strictEqual()

严格的类型和值比较.

14

throws()

测试回调是否抛出异常,并可选择比较抛出的错误.

让我们试着在一个例子中介绍上面提到的大部分方法.

<html>
   <head>
      <meta charset = "utf-8">
      <title>QUnit basic example</title>
      <link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
      <script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
   </head>
   
   <body>
      <div id = "qunit"></div>
      <div id = "qunit-fixture"></div> 
      <script>
         QUnit.test( "TestSuite", function( assert ) {
            //test data
            var str1 = "abc";
            var str2 = "abc";
            var str3 = null;
            var val1 = 5;
            var val2 = 6;
            var expectedArray = ["one", "two", "three"];
            var resultArray =  ["one", "two", "three"];

            //Check that two objects are equal
            assert.equal(str1, str2, "Strings passed are equal.");
			
            //Check that two objects are not equal
            assert.notEqual(str1,str3, "Strings passed are not equal.");

            //Check that a condition is true
            assert.ok(val1 < val2, val1 + " is less than " + val2);
			
            //Check that a condition is false
            assert.notOk(val1 > val2, val2 + " is not less than " + val1);

            //Check whether two arrays are equal to each other.
            assert.deepEqual(expectedArray, resultArray ,"Arrays passed are equal.");
			
            //Check whether two arrays are equal to each other.
            assert.notDeepEqual(expectedArray, ["one", "two"],
               "Arrays passed are not equal.");			
         });
      </script>
   </body>
</html>

验证输出

您应该看到以下结果 :