Jasmine

基本概念


suites

suites表示一個測試集,以函數(shù)describe封裝

describe

describe 是 Jasmine 的全局函數(shù),作為一個 Test Suite 的開始
它通常有 2 個參數(shù):字符串和方法
字符串 -> 特定 Suite 的名字和標(biāo)題
方法 -> 實現(xiàn) Suite 的代碼

describe("This is an exmaple suite", function() {
  it("contains spec with an expectation", function() {
    //測試true是否等于true
    expect(true).toBe(true);
    expect(false).toBe(false);
    expect(false).not.toBe(true);
  });
});

Specs

Specs 通過調(diào)用 it 的全局函數(shù)來定義
it和describe的參數(shù)相同
每個 Spec 包含一個或多個 expectations 來測試需要測試代碼

Expectations

Expectations 是由方法 expect 來定義
一值代表實際值,二值代表期望值

Matchers

Matcher實現(xiàn)了斷言的比較操作
可以在expect調(diào)用Matcher前加上not來實現(xiàn)一個否定的斷言(expect(a).not.toBe(false);)
常見的matchers:
toBe():相當(dāng)于===比較
toNotBe()
toBeDefined():檢查變量或?qū)傩允欠褚崖暶髑屹x值
toBeUndefined()
toBeNull():是否是null
toBeTruthy():如果轉(zhuǎn)換為布爾值,是否為true
toBeFalsy()
toBeLessThan():數(shù)值比較,小于
toBeGreaterThan():數(shù)值比較,大于
toEqual():相當(dāng)于==

注意與toBe()的區(qū)別:
一個新建的Object不是(not to be)另一個新建的Object,但是它們是相等(to equal)的

toNotEqual()
toContain():數(shù)組中是否包含元素(值)只能用于數(shù)組,不能用于對象
toBeCloseTo():數(shù)值比較時定義精度,先四舍五入后再比較

//true
it("The 'toBeCloseTo' matcher is for precision math comparison", function() {  
  var pi = 3.1415926,     
    e = 2.78;  
  expect(pi).not.toBeCloseTo(e, 2);  //第一個參數(shù)為比較數(shù),第二個參數(shù)定義精度
  expect(pi).toBeCloseTo(e, 0);
});

toHaveBeenCalled()
toHaveBeenCalledWith()
toMatch():按正則表達(dá)式匹配
toNotMatch()
toThrow():檢驗一個函數(shù)是否會拋出一個錯誤

Setup and Teardown

Jasmine 提供了全局的方法實現(xiàn)清理操作
在describe函數(shù)中,
beforeEach():每個Spec執(zhí)行之前執(zhí)行
afterEach(): 每個Spec執(zhí)行之后執(zhí)行。
beforeAll():所有的Specs執(zhí)行之前執(zhí)行,但只執(zhí)行一次
afterAll():所有的Specs執(zhí)行之后執(zhí)行,但只執(zhí)行一次

嵌套代碼塊

describe 可以嵌套, Specs 可以定義在任何一層
一個 suite 可以由一組樹狀的方法組成
在每個 spec 執(zhí)行前,Jasmine 遍歷樹結(jié)構(gòu),按順序執(zhí)行每個 beforeEach 方法,Spec 執(zhí)行后,Jasmine 同樣執(zhí)行相應(yīng)的 afterEach

跳過測試代碼塊

Suites 和 Specs 分別可以用 xdescribe 和 xit 方法來禁用和掛起
被Disabled的Suites在執(zhí)行中會被跳過,該Suite的結(jié)果也不會顯示在結(jié)果集中
被Pending的Spec不會被執(zhí)行,但是Spec的名字會在結(jié)果集中顯示,只是標(biāo)記為Pending

xdescribe("An example of xdescribe.", function() {
  var gVar;

  beforeEach(function() {
    gVar = 3.6;
    gVar += 1;
  });

  xit(" and xit", function() {
    expect(gVar).toEqual(4.6);
  });
});

一個沒有定義函數(shù)體的Sepc也會在結(jié)果集中被標(biāo)記為Pending
如果在Spec的函數(shù)體中調(diào)用pending()函數(shù),那么該Spec也會被標(biāo)記為Pending。pending()函數(shù)接受一個字符串參數(shù),該參數(shù)會在結(jié)果集中顯示在PENDING WITH MESSAGE:之后,作為為何被Pending的原因

describe("Pending specs", function() {

  xit("can be declared 'xit'", function() {
    expect(true).toBe(false);
  });

  it("can be declared with 'it' but without a function");
  
  it("can be declared by calling 'pending' in the spec body", function() {
    expect(true).toBe(false);
    pending('this is why it is pending');
  });
});

Spy

Spy能監(jiān)測任何function的調(diào)用和方法參數(shù)的調(diào)用痕跡。需使用2個特殊的Matcher:

  • toHaveBeenCalled:可以檢查function是否被調(diào)用過
  • toHaveBeenCalledWith: 可以檢查傳入?yún)?shù)是否被作為參數(shù)調(diào)用過

spyOn
使用 spyOn(obj,'function') 來為 obj 的 function 方法聲明一個Spy
對Spy函數(shù)的調(diào)用并不會影響真實的值

describe("A spy", function() {
    var foo, bar = null; 
    beforeEach(function() { 
      foo = { 
        setBar: function(value) { 
          bar = value; 
        } 
      }; 

      spyOn(foo, 'setBar'); 

      foo.setBar(123); 
      foo.setBar(456, 'another param'); 
    }); 
    it("tracks that the spy was called", function() { 
     expect(foo.setBar).toHaveBeenCalled(); 
    }); 
    it("tracks all the arguments of its calls", function() { 
      expect(foo.setBar).toHaveBeenCalledWith(123); 
      expect(foo.setBar).toHaveBeenCalledWith(456, 'another param'); 
    }); 
    it("stops all execution on a function", function() { 
      // Spy的調(diào)用并不會影響真實的值,所以bar仍然是null
      expect(bar).toBeNull(); 
    });
});

and.callThrough
如果在spyOn之后鏈?zhǔn)秸{(diào)用and.callThrough,那么Spy除了跟蹤所有的函數(shù)調(diào)用外,還會直接調(diào)用函數(shù)額真實實現(xiàn),因此Spy返回的值就是函數(shù)調(diào)用后實際的值了

  ... 
  spyOn(foo, 'getBar').and.callThrough(); 
  foo.setBar(123); 
  fetchedBar = foo.getBar(); 
  it("tracks that the spy was called", function() { 
    expect(foo.getBar).toHaveBeenCalled(); 
  }); 
  it("should not effect other functions", function() { 
    expect(bar).toEqual(123); 
  }); 
  it("when called returns the requested value", function() { 
    expect(fetchedBar).toEqual(123); 
  });
});

and.stub
在調(diào)用and.callThrough后,如果你想阻止spi繼續(xù)對實際值產(chǎn)生影響,你可以調(diào)用and.stub。也就是說,and.stub是將spi對實際實現(xiàn)的影響還原到最終的狀態(tài)——不影響實際值

spyOn(foo, 'setBar').and.callThrough();
foo.setBar(123);
// 實際的bar=123
expect(bar).toEqual(123);
// 調(diào)用and.stub()后,之后調(diào)用foo.setBar將不會影響bar的值。
foo.setBar.and.stub();
foo.setBar(456);
expect(bar).toBe(123);
bar = null;
foo.setBar(123);
expect(bar).toBe(null);

全局匹配謂詞


jasime.any
參數(shù)為一個構(gòu)造函數(shù),用于檢測該參數(shù)是否與實際值所對應(yīng)的構(gòu)造函數(shù)相匹配

describe("jasmine.any", function() { 
  it("matches any value", function() { 
    expect({}).toEqual(jasmine.any(Object)); 
    expect(12).toEqual(jasmine.any(Number)); 
  }); 
  describe("when used with a spy", function() { 
    it("is useful for comparing arguments", function() { 
      var foo = jasmine.createSpy('foo'); 
      foo(12, function() { return true; }); 
      expect(foo).toHaveBeenCalledWith(jasmine.any(Number), jasmine.any(Function)); 
    }); 
  });
});

jasime.anything
用于檢測實際值是否為 null 或 undefined ,如果不為 null 或 undefined,則返回true

it("matches anything", function() { 
  expect(1).toEqual(jasmine.anything());
});

jasmine.objectContaining
用于檢測實際Object值中是否存在特定key/value對。

var foo;
beforeEach(function() {
  foo = {
    a: 1,
    b: 2,
    bar: "baz"
  };
 });
it("matches objects with the expect key/value pairs", function() {
  expect(foo).toEqual(jasmine.objectContaining({ bar: "baz" }));
  expect(foo).not.toEqual(jasmine.objectContaining({ c: 37 }));
});

jasmine.arrayContaining
用于檢測實際Array值中是否存在特定值。


this值

除了在describe函數(shù)開始定義變量,用于各it函數(shù)共享數(shù)據(jù)外,還可以通過this關(guān)鍵字來共享數(shù)據(jù)。
在在每一個Spec的生命周期(beforeEach->it->afterEach)的開始,都將有一個空的this對象(在開始下一個Spec周期時,this會被重置為空對象)。

參考目錄


JavaScript 單元測試框架:Jasmine 初探
JavaScript單元測試框架-Jasmine
web前端開發(fā)七武器—Jasmine入門教程(上)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容