Jest

安裝:javascript

npm istall --save-dev jest  ||  yarn add --dev jesthtml

栗子:java

//sum.js
function sum(a,b){
   return a+b;  
}
module.exports =  sum;

//sum.test.js
const sum =  require('./sum');
test('adds 1+2 to equal 3',() => {
   expect(sum(1,2)).toBe(3) 
})

運行: npm testreact

Using Matchersandroid

普通匹配器git

test('two plus two is four',() => {
   expect(2+2).toBe(4); // expect 返回一個指望的對象,toBe使用 ===來測試徹底相等
})

test('adding positive number is not zero',() => {
for(let a = 1; a<10; a++){
for(let b = 1; b<10; b++){
expect(a+b).not.toBe(0);
}
}
})

檢查對象使用toEqualgithub

test('object assignment',() => {
   const data = {one:1};
   data['two'] = 2;
   expect(data).toEqual({one:1,two:2}) 
})

經常使用屬性正則表達式

toBeNull:只匹配nullexpress

toBeUndefined:只匹配undefinednpm

toBeDefined與toBeUndefined相反

toBeTruthy:匹配任何if語句爲真

toBeFalsy:匹配任何if語句爲假

test('null',() => {
  const n =null
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
})

匹配數字

test('two plus two', () => {
 const value = 2+2;
 expect(value).toBeGreaterThan(3);
 expect(value).toBeGreaterThanOrEqual(3.5);
 expect(value).toBeLessThan(5);
 ecpect(value).toBeLessThanOrEqual(4.5);   

// toBe and toEqual are equivalent for numbers
  expect(value).toBe(4);
  expect(value).toEqual(4);

  expect(value).toBeCloseTo(0.3)  //用於比較浮點數的相等
})

匹配字符串

//檢查對具備toMatch正則表達式的字符串

test('there is no I in team', () => {
  expect('team').not.toMatch(/I/);
});

test('but there is a "stop" in christoph', () =>{
 expect('christoph').toMatch(/stop/)
})

 數組

//檢查數組是否包含特定子項使用 toContain
const shoppingList = {
  'd','c'
}

test('the shopping list has beer on it',() =>{
 expect(shoppingList).toContain('d')
})

測試特定函數拋出一個錯誤使用toThrow

function compileAndroidCode(){
   throw new ConfigError('you are using the wrong JDK')
}

test('compiling android goes as expected',() => {
  expect(compileAndroidCode).toThrow();
  expect(compileAndroidCode).toThrow(ConfigError);

  // You can also use the exact error message or a regexp
  expect(compileAndroidCode).toThrow('you are using the wrong JDK');
  expect(compileAndroidCode).toThrow(/JDK/);
})

 測試中須要反覆測試的方法

beforeEach(() =>{
    //測試前要執行的東西
})

afterEach(() => {
 //測試後要執行的東西
})

測試中只須要設置一次的方法

beforeAll(() => {//測試前執行的方法})

afterAll(() =>{//測試後執行的方法})

describe:對測試進行分組

describe('my name is describe',()=>{ 

//全部相似於beforeEach的,它的做用域都只在當前的這個describe

 beforeEach(() =>{})
})

只運行當前的測試

test.only('This will be the only test that runs',() =>{
//要測試的內容
})

測試中測試方法時

//mock function(模擬方法)

myFuntion(items,callback) =>{
  for(let i = 0;i<items.length;i++){
     callback(items[index])
  }
}

const mockCallback = jest.fn();

myFuntion(0,1,mockCallback );

expect(mockCallback.mock.calls.length).toBe(2);

//模擬方法還能夠用於在測試期間向您的代碼注入測試值。
const myMock = jest.fn(); console.log(myMock()); // > undefined myMock.mockReturnValueOnce(10) .mockReturnValueOnce('x') .mockReturnValue(true); console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true

斷言方法是否被調到

//這個方法至少被調用一次
expect(myfunction).toBeCalled();

//這個方法至少被調用一次,arg1和arg2是傳到該方法的參數
expect(myfunction).toBeCalledWith(arg1,arg2)

//這個方法最後被調用,arg1和arg2是傳到該方法的參數
expect(myfunction).lastCalledWith(arg1,arg2)

//全部調用和mock的名稱都是做爲快照編寫的
expect(myfunction).toMatchSnapshot();

 全局方法和對象

afterAll(fn):在此文件中的全部測試都完成後,運行的功能。一般用在你想要清理一些在測試之間共享的全局設置狀態。若是它在一個describe塊裏,它將在描述(describe)塊末尾運行

const globalDataBase = makeGlobalDatabase();

function cleanUpDataBase(db){db.cleanUp();}

afterAll(() =>{cleanUpDataBase(globalDataBase)});

test('can find things',() => {
   return globalDataBase.find('thing',{},results =>{
      expect(results.length).toBeGreaterThan(0);
   })    
})

afterEach(fn):不一樣於afterAll,它是在每個test運行完以後運行。若是這個test裏有異步返回的話,就能返回以後再運行。這個一般用在你想要清理test運行中的一些臨時狀態。若是它存在在一個describe(描述)塊裏,那麼它的做用域就是這個描述塊。

afterEach(() =>{//要清除的東西})  //每一個test運行以後都會被調用一次

test('test 1', () =>{//測試邏輯1})

test('test 2',() =>{//測試邏輯2})

beforeAll(fn):它在test以前運行,若是它裏面包含異步那麼將在返回值以後再運行test。一般用在想要在運行test以前準備一些全局狀態時。若是它存在於一個描述(describe)塊,那麼它將在這個描述塊開始的時候執行。

beforAll(() =>{//要準備的全局數據})

test('test 1',() =>{
 //beforeAll運行完以後,纔會被執行
})

 beforeEach(fn):不一樣於beforAll。它是在每一個test以前都會運行一邊,若是存在異步有返回值的以後纔會調用test。經常使用於在測試運行以前想要重置一些全局狀態的時候。若是它存在於一個描述(describe)塊,那麼它的做用域只在這個描述塊中。

beforeEach(() =>{//要清除的東西})  //每一個test運行以前都會被調用一次

test('test 1', () =>{//測試邏輯1})

test('test 2',() =>{//測試邏輯2})

 describe.only(name,fn):若是一個測試文件裏有多個describe塊,你只想運行某一個此時你就能夠用它。

describe.only('just run this',() =>{
  //test方法
})

describe.only('no run this',() => {//test方法})

describe.skip(name,fn):在一個測試文件裏若是你不想要運行某個describe塊的話,可使用它

describe('this run',() => {//test function})

describe.skip('this not run', () =>{//test function})

require.requireActual(moduleName):返回實際模塊而不是模擬的,繞過全部檢查模塊是否應該接收到模擬實現。

require.requireMock(moduleName):返回模擬的模塊,而不是實際的模塊,繞過全部檢查模塊是否應該正常要求

test(name,fn)別名it(name,fn):這裏面寫要測試的內容

test.only(name,fn)別名it.only(name,fn)或fit(name,fn):若是隻想要單獨測這個test方法,能夠用它。

test.skip(name,fn)別名it.skip(name,fn)或xit(name,fn)或xtest(name,fn):若是想要跳過這個test不執行,能夠用它。

expect

expect.extend(matchers):將自定義的matchers(匹配器)添加到jest。

expect.extend({
  toBeDivisibleBy(received,argument){
    const pass = (received % argument == 0);
    if(pass){
       return {
          message: () => (`expected ${received} not to be divisible by ${argument}`),
          pass: true,
       }
    } else {
          return {
              message: () => (`expected ${received}  to be divisible by ${argument}`),
              pass: false
          }
       }
  }
})

test('handle toBeDivisibleBy matcher',() => {
  expect(100).toBeDivisibleBy(2);
  expect(101).not.toBeDivisibleBy(2);
})

expect.anything():匹配任何不是null或者undefined的值,你能夠把它用在toEqual或toBeCalledWith裏。

test('map calls its argument with a non-null argument', () => {
  const mock = jest.fn();
  [1].map(mock);
  expect(mock).toBeCalledWith(expect.anything());
})

expect.any(constructor):匹配任何由給定構造函數建立的內容。

randocall (fn) {
  return fn(Math.floor(Math.random() *6 +1))
}

test('randocall calls its callback with a number', () =>{
   const mock =jest.fn();
   randocall(mock);
   expect(mock).toBeCalledWith(expect.any(Number))

})

 expect.arrayContaining(array):匹配一個測試返回的數組,它包含全部預期的元素。就是說,這個預期數組是測試返回數組的一個子集。

const expected = [1,2,3,4,5,6]

it('不匹配,多出了意想不到的7',() => {
  expect([4,1,6,3,5,2,5,4,6]).toEqual(expect.arrayContaining(expected))
})

it('不匹配,缺乏2', () =>{
  expect([4,1,6,3,5,4,6]).not.toEqual(expect.arrayContaining(expected))
})

 expect.assertions(number):常常被用在當你的一個測試中須要調兩個或者兩個以上的異步時,你能夠用它來判斷,以確保回調中的斷言被調用。

test('doAsync calls both callbacks', () =>{

  expect.assertions(2);

  callback1(data) {
     expect(data).toBeTruthy(); 
  }
    
  callback2(data){
    expect(data).toBeTruthy();
  }

  doAsync(callback1,callback2)
})

expect.hasAssertions():一般用在有異步方法調用的測試裏,來斷言至少一個回調。

test('test hasAssertions',() => {
  expect.hasAssertions();
  prepareState(state => {
    expect(validateState(state)).toBeTruthy();
  })
  return waitOnState();
})

expect.objectContaining(object):匹配一個測試返回的對象,它包含全部預期的元素。就是說,這個預期對象是測試返回數組的一個子集。

test('test objectContaining', () => {
   const onPress = jest.fn();
simulatePresses(onPress);
expect(onPress).toBeCalledWith(expect.objectContaining({
x:expect.any(Number);
y:expect.any(Number);
})) })

 expect.stringContaining(string):匹配任何包含精確預期字符串的接收字符串。

 expect.StringMatching(regexp(正則表達式)):將返回值與預期的正則進行比較。它常使用在toEqual,toBeCalledWith,arrayContaining,objectContaining,toMatchObject

describe('test stringMatching', () => {
  const expected = [
    expect.stringMatching(/^Alic/),
    expect.stringMatching(/^[BR]ob/),
  ];
  it('matches even if received contains additional elements', ()=> {
     expect(['Alicia','Roberto','Evelina']).toEqual(expect.arrayContaining(expected));
  });
  
  it('does not match if received does not contain expected elements', () => {
    expect(['Roberto','Evelina']).not.toEqual(expect.arrayContaining(expected))
  })

})

 expect.addSnapshotSerializer(serializer)

import serializer from 'my-serializer-module'
expect.addSnapshotSerializer(serializer);

.not:驗證一段邏輯是否是沒有被執行

test('the best flavor is not coconut',() =>{
   expect(bestLaCroixFlavor()).not.toBe('coconut')
})

.resolves:

Use resolves to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails.

For example, this code tests that the promise resolves and that the resulting value is 'lemon':

test('resolves to lemon', () =>{
  //make sure to add a return statement
  return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
})

test('resolves to lemon',async () =>{
  await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
  await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
})

 rejects:斷言一個異步方法是否被拒絕,若是這個異步被執行則斷言失敗

test('rejects to octopus', () => {
  return expect(Promise.reject('octopus')).rejects.toBe('octopus')
})

test('rejects to octopus',async () =>{
  await expect(Promise.reject('octopus')).rejects.toBe('octopus')
})

toBe(value):檢測一個值是否是你的預期相似於===,它不能用於對比浮點數,若是想對於浮點數用toBeCloseTo

const can = {
  name: 'pamplemousse',
  ounces:12,
}
describe('the can',() => {
  it('has 12 ounce' ,() =>{expect(can.ounces.toBe(12))})
})

 .toHaveBeenCalled():(別名.toBeCalled())測試方法被調用

describe('test toHaveBeenCalled', () => {
  
 test('this function not toBeCalled', () => {
     const drink = jest.fn();
     drinkAll(drink,'lemon');
     expect(drink).toHaveBeenCalled();
  });
  
  test('this function toBeCalled', () => {
     const drink = ject.fn();
     drinkAll(drink,'octopus');
     expect(drink).not.toHaveBeenCalled();
   }) 
})

.toHaveBeenCalledTimes(number):測試方法是否在規定的時間內被調用

test('drinkEach drinks each drink', () => {
   const drink = jest.fn();
   expect(drink).toHaveBeenCalledTimes(2);
})

.toHaveBeenCalledWith(arg1,arg2...):(別名:toBeCalledWith())測試帶有特定參數的方法是否被調用

test('the function to be call,when the arguments is true', () => {
  const bool = true;
  const f = jest.fn();
  expect(f).toBeCalledWith(bool);
})

.toHaveBeenLastCalledWith(arg1,arg2,...):(別名:.lastCalledWith(arg1,arg2,..))測試方法中的某個參數是不是最後一個被調用

test('applying to all flavors does mango last',() => {
 const drink = jest.fn();
 applyToAllFlavors(drink);
 expect(drink).toHaveBeenLastCalledWith('mango');
})

.toBeCloseTo(number,numDigits):測試浮點數

test('test float number', () => {
 expect(0.2+0.1).toBeCloseTo(0.3,5) //精確到小數點後面5位,不寫默認是2
})

.toBeDefined():測試一個方法是否有返回值(返回值任意)

it('test the function return something', () => {
  expect(fetchNewFlavorIdea()).toBeDefined();
// expect(fetchNewFlavorIdea()).not.toBe(undefined); //也能夠寫成這樣,可是不推薦 })

 .toBeFalsy():判斷一個boolean值,是否是false

it('drinking la croix does not lead to errors', () => {
 expect(getErrors()).toBeFalsy();
})

toBeGreaterThan(number):用於比較浮點數

test('test toBeGreaterThan', () => {
  expect(11.2).toBeGreaterThan(10);
})

.toBeGreaterThanOrEqual(number):比較浮點數,returns a value of at least 12 ounces

it('ounces per can is at least 12', () => {
 expect(ouncesPerCan()).toBeGreaterOrEqual(12)
})

 .toBeLessThan(number):比較浮點數,returns a value of less than 20 ounces.

it('ounces per can is less than 20', () =>{
 expect(ouncesPerCan()).toBeLessThan(20);
})

.toBeLessThanOrEqual(number):比較浮點數,returns a value of at most 12 ounces

test('ounces per can is at most 12', () => {
  expect(ouncesPreCan()).toBeLessThanOrEqual(12)
})

.toBeInstanceOf(Class):檢測對象是否爲類的實例

calss A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function)

.toBeNull():檢查是否返回null;相似於.toBe(null)

function bloop() {return null;}

it('bloop returns  null', () => {
 expect(bloop()).toBeNull();
})

.toBeTruthy():判斷是否返回true

it('test toBeTruthy', () => {
 expect(true).toBeTruthy();
})

.toBeUndefined():判斷返回值是否undefined

it('test undefined',() => {
 expect(undefined).toBeUndefined();
})

.toContain(item):檢查某個值是否包含在該數組中

it('the flavor list contains lime', () => {
  expect(['a','b']).toContain('a')
})

.toContainEqual(item):檢查具備特定結構和值的元素是否包含在數據中

it('test contain', () =>{
 const testValue = {bol:true}
 expect([{bol:true},{sour:false}]).toContainEqual(testValue)
})

 .toEqual(value):判斷兩個值是否相等

it('is same', () =>{
 expect('aa').toEqual('aa')
})

 .toHaveLength(number):檢測某值是否有長度

expect([1,2,3]).toHaveLength(3);

expect('abc').toHaveLength(3);

expect('').not.toHaveLength(5);

 .toMatch(regexpOrString):檢查字符串是否與正則表達式匹配

describe('an essay on the best flavor', () => {
  it('mentions grapefruit', () => {
     expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
expect('grapefruits').toMatch('fruit'); }); });

 .toMatchObject(object):檢測一個javaScript對象是否匹配對象屬性的子集。它將匹配接受的對象,這些對象的屬性不在預期對象中。你還能夠傳遞一個對象數組,在這種狀況下,只有在接收到的數組中的每一個對象匹配預期數組中的對應對象時,該方法纔會返回true。若是你想要檢查這兩個數組匹配它們的元素數量,而不是array包含的元素,這將很是有用。

const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};
const desiredHouse = {
  bath: true,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    wallColor: expect.stringMatching(/white|yellow/),
  },
};

test('the house has my desired features', () => {
  expect(houseForSale).toMatchObject(desiredHouse);
});

describe('toMatchObject applied to arrays arrays', () => { test('the number of elements must match exactly', () => { expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]); }); // .arrayContaining "matches a received array which contains elements that // are *not* in the expected array" test('.toMatchObject does not allow extra elements', () => { expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}]); }); test('.toMatchObject is called for each elements, so extra object properties are okay', () => { expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([ {foo: 'bar'}, {baz: 1}, ]); }); });
 

.toHaveProperty(keyPath,value):檢查對象裏是否包含key或value

 

const houseForSale = {
 bath:true,
 bedrooms:4,
 kitchen: {
   amenities:['oven','stove','washer'],
   area:20,
   wallColor:'white'
 }
}

it('this house has my desired features', () => {
  //simple Referencing
  expect(houseForSale).toHaveProperty('bath');
  expect(houseForSale).toHaveProperty('pool');
  expect(houseForSale).toHaveProperty('bedrooms',4);

//deep referencing using dot notation
expect(houseForSale).not.toHaveProperty('kitchen.area',20);
expect(houseForSale).toHaveProperty('kitchen.amenities',[
 'oven',
    'stove',
    'washer',
  ]);

  expect(houseForSale).not.toHaveProperty('kitchen.open');

})

.toMatchSnapshot(optionalString) #

This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.

You can also specify an optional snapshot name. Otherwise, the name is inferred from the test.

Note: While snapshot testing is most commonly used with React components, any serializable value can be used as a snapshot.

 

.toThrow(error):別名toThrowError(error):測試一個方法的拋出

test('throws on octopus' , () => {
 expect(() => {
    drinkFlavor('octopus');
 }).toThrow();
})

function drinkFlavor(flavor){
if(flavor === 'octopus'){
throw new DisgustingFlavorError('yuck,octopus flavor');
}
}
it('throws on octopus', () => {
  function testFun(){
drinkFlavor('octopus') //必須將其寫着方法裏,不然沒法捕獲錯誤,斷言失敗
}
expect(testFun).toThrowError('yuck,octopus flavor')
expect(testFun).toThrowError(/yuck/)
expect(testFun).toThrowError(DisgustingFlavorError)
})

 .toThrowErrorMatchingSnapshot():測試函數在調用時拋出一個匹配最近快照的錯誤。

function drinkFlavor(flavor){
 if(flavor === 'octopus'){
   throw new DisgustingFlavorError('yuck,octopus flavor')
 }
}

it('throws on octopus', () => {
  function drinkOctopus() {
    drinkFlavor('octopus')
  }
  expect(drinkOctopus).toThrowErrorMatchingSnapshot();
//exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`;
})

 

EDIT THIS DOC

Expect

When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.

Methods #


Reference #

expect(value) #

The expect function is used every time you want to test a value. You will rarely call expect by itself. Instead, you will use expect along with a "matcher" function to assert something about a value.

It's easier to understand this with an example. Let's say you have a method bestLaCroixFlavor() which is supposed to return the string 'grapefruit'. Here's how you would test that:

test('the best flavor is grapefruit', () => {
  expect(bestLaCroixFlavor()).toBe('grapefruit');
});

In this case, toBe is the matcher function. There are a lot of different matcher functions, documented below, to help you test different things.

The argument to expect should be the value that your code produces, and any argument to the matcher should be the correct value. If you mix them up, your tests will still work, but the error messages on failing tests will look strange.

expect.extend(matchers) #

You can use expect.extend to add your own matchers to Jest. For example, let's say that you're testing a number theory library and you're frequently asserting that numbers are divisible by other numbers. You could abstract that into a toBeDivisibleBy matcher:

expect.extend({
  toBeDivisibleBy(received, argument) {
    const pass = received % argument == 0;
    if (pass) {
      return {
        message: () =>
          `expected ${received} not to be divisible by ${argument}`,
        pass: true,
      };
    } else {
      return {
        message: () => `expected ${received} to be divisible by ${argument}`,
        pass: false,
      };
    }
  },
});

test('even and odd numbers', () => {
  expect(100).toBeDivisibleBy(2);
  expect(101).not.toBeDivisibleBy(2);
});

Matchers should return an object with two keys. pass indicates whether there was a match or not, and message provides a function with no arguments that returns an error message in case of failure. Thus, when pass is false, message should return the error message for when expect(x).yourMatcher() fails. And when pass is true, message should return the error message for when expect(x).not.yourMatcher() fails.

These helper functions can be found on this inside a custom matcher:

this.isNot #

A boolean to let you know this matcher was called with the negated .not modifier allowing you to flip your assertion.

this.equals(a, b) #

This is a deep-equality function that will return true if two objects have the same values (recursively).

this.utils #

There are a number of helpful tools exposed on this.utils primarily consisting of the exports fromjest-matcher-utils.

The most useful ones are matcherHintprintExpected and printReceived to format the error messages nicely. For example, take a look at the implementation for the toBe matcher:

const diff = require('jest-diff');
expect.extend({
  toBe(received, expected) {
    const pass = Object.is(received, expected);

    const message = pass
      ? () =>
          this.utils.matcherHint('.not.toBe') +
          '\n\n' +
          `Expected value to not be (using Object.is):\n` +
          ` ${this.utils.printExpected(expected)}\n` +
          `Received:\n` +
          ` ${this.utils.printReceived(received)}`
      : () => {
          const diffString = diff(expected, received, {
            expand: this.expand,
          });
          return (
            this.utils.matcherHint('.toBe') +
            '\n\n' +
            `Expected value to be (using Object.is):\n` +
            ` ${this.utils.printExpected(expected)}\n` +
            `Received:\n` +
            ` ${this.utils.printReceived(received)}` +
            (diffString ? `\n\nDifference:\n\n${diffString}` : '')
          );
        };

    return {actual: received, message, pass};
  },
});

This will print something like this:

  expect(received).toBe(expected)

    Expected value to be (using Object.is):
      "banana"
    Received:
      "apple"

When an assertion fails, the error message should give as much signal as necessary to the user so they can resolve their issue quickly. You should craft a precise failure message to make sure users of your custom assertions have a good developer experience.

expect.anything() #

expect.anything() matches anything but null or undefined. You can use it inside toEqual or toBeCalledWith instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument:

test('map calls its argument with a non-null argument', () => {
  const mock = jest.fn();
  [1].map(mock);
  expect(mock).toBeCalledWith(expect.anything());
});

expect.any(constructor) #

expect.any(constructor) matches anything that was created with the given constructor. You can use it inside toEqual or toBeCalledWith instead of a literal value. For example, if you want to check that a mock function is called with a number:

function randocall(fn) {
  return fn(Math.floor(Math.random() * 6 + 1));
}

test('randocall calls its callback with a number', () => {
  const mock = jest.fn();
  randocall(mock);
  expect(mock).toBeCalledWith(expect.any(Number));
});

expect.arrayContaining(array) #

expect.arrayContaining(array) matches a received array which contains all of the elements in the expected array. That is, the expected array is a subset of the received array. Therefore, it matches a received array which contains elements that are not in the expected array.

You can use it instead of a literal value:

  • in toEqual or toBeCalledWith
  • to match a property in objectContaining or toMatchObject
describe('arrayContaining', () => {
  const expected = ['Alice', 'Bob'];
  it('matches even if received contains additional elements', () => {
    expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected));
  });
  it('does not match if received does not contain expected elements', () => {
    expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected));
  });
});
describe('Beware of a misunderstanding! A sequence of dice rolls', () => {
  const expected = [1, 2, 3, 4, 5, 6];
  it('matches even with an unexpected number 7', () => {
    expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual(
      expect.arrayContaining(expected),
    );
  });
  it('does not match without an expected number 2', () => {
    expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual(
      expect.arrayContaining(expected),
    );
  });
});

expect.assertions(number) #

expect.assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

For example, let's say that we have a function doAsync that receives two callbacks callback1 and callback2, it will asynchronously call both of them in an unknown order. We can test this with:

test('doAsync calls both callbacks', () => {
  expect.assertions(2);
  function callback1(data) {
    expect(data).toBeTruthy();
  }
  function callback2(data) {
    expect(data).toBeTruthy();
  }

  doAsync(callback1, callback2);
});

The expect.assertions(2) call ensures that both callbacks actually get called.

expect.hasAssertions() #

expect.hasAssertions() verifies that at least one assertion is called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

For example, let's say that we have a few functions that all deal with state. prepareState calls a callback with a state object, validateState runs on that state object, and waitOnState returns a promise that waits until all prepareState callbacks complete. We can test this with:

test('prepareState prepares a valid state', () => {
  expect.hasAssertions();
  prepareState(state => {
    expect(validateState(state)).toBeTruthy();
  });
  return waitOnState();
});

The expect.hasAssertions() call ensures that the prepareState callback actually gets called.

expect.objectContaining(object) #

expect.objectContaining(object) matches any received object that recursively matches the expected properties. That is, the expected object is a subset of the received object. Therefore, it matches a received object which contains properties that are not in the expected object.

Instead of literal property values in the expected object, you can use matchers, expect.anything(), and so on.

For example, let's say that we expect an onPress function to be called with an Event object, and all we need to verify is that the event has event.x and event.y properties. We can do that with:

test('onPress gets called with the right thing', () => {
  const onPress = jest.fn();
  simulatePresses(onPress);
  expect(onPress).toBeCalledWith(
    expect.objectContaining({
      x: expect.any(Number),
      y: expect.any(Number),
    }),
  );
});

expect.stringContaining(string) #

available in Jest 19.0.0+ #

expect.stringContaining(string) matches any received string that contains the exact expected string.

expect.stringMatching(regexp) #

expect.stringMatching(regexp) matches any received string that matches the expected regexp.

You can use it instead of a literal value:

  • in toEqual or toBeCalledWith
  • to match an element in arrayContaining
  • to match a property in objectContaining or toMatchObject

This example also shows how you can nest multiple asymmetric matchers, with expect.stringMatchinginside the expect.arrayContaining.

describe('stringMatching in arrayContaining', () => {
  const expected = [
    expect.stringMatching(/^Alic/),
    expect.stringMatching(/^[BR]ob/),
  ];
  it('matches even if received contains additional elements', () => {
    expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
      expect.arrayContaining(expected),
    );
  });
  it('does not match if received does not contain expected elements', () => {
    expect(['Roberto', 'Evelina']).not.toEqual(
      expect.arrayContaining(expected),
    );
  });
});

expect.addSnapshotSerializer(serializer) #

You can call expect.addSnapshotSerializer to add a module that formats application-specific data structures.

For an individual test file, an added module precedes any modules from snapshotSerializersconfiguration, which precede the default snapshot serializers for built-in JavaScript types and for React elements. The last module added is the first module tested.

import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);

// affects expect(value).toMatchSnapshot() assertions in the test file

If you add a snapshot serializer in individual test files instead of to adding it to snapshotSerializersconfiguration:

  • You make the dependency explicit instead of implicit.
  • You avoid limits to configuration that might cause you to eject from create-react-app.

See configuring Jest for more information.

.not #

If you know how to test something, .not lets you test its opposite. For example, this code tests that the best La Croix flavor is not coconut:

test('the best flavor is not coconut', () => {
  expect(bestLaCroixFlavor()).not.toBe('coconut');
});

.resolves #

available in Jest 20.0.0+ #

Use resolves to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails.

For example, this code tests that the promise resolves and that the resulting value is 'lemon':

test('resolves to lemon', () => {
  // make sure to add a return statement
  return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});

Alternatively, you can use async/await in combination with .resolves:

test('resolves to lemon', async () => {
  await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
  await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
});

.rejects #

available in Jest 20.0.0+ #

Use .rejects to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.

For example, this code tests that the promise rejects with reason 'octopus':

test('rejects to octopus', () => {
  // make sure to add a return statement
  return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
    'octopus',
  );
});

Alternatively, you can use async/await in combination with .rejects.

test('rejects to octopus', async () => {
  await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
});

.toBe(value) #

toBe just checks that a value is what you expect. It uses Object.is to check exact equality.

For example, this code will validate some properties of the can object:

const can = {
  name: 'pamplemousse',
  ounces: 12,
};

describe('the can', () => {
  test('has 12 ounces', () => {
    expect(can.ounces).toBe(12);
  });

  test('has a sophisticated name', () => {
    expect(can.name).toBe('pamplemousse');
  });
});

Don't use toBe with floating-point numbers. For example, due to rounding, in JavaScript 0.2 + 0.1 is not strictly equal to 0.3. If you have floating point numbers, try .toBeCloseTo instead.

.toHaveBeenCalled() #

Also under the alias: .toBeCalled()

Use .toHaveBeenCalled to ensure that a mock function got called.

For example, let's say you have a drinkAll(drink, flavor) function that takes a drink function and applies it to all available beverages. You might want to check that drink gets called for 'lemon', but not for 'octopus', because 'octopus' flavor is really weird and why would anything be octopus-flavored? You can do that with this test suite:

describe('drinkAll', () => {
  test('drinks something lemon-flavored', () => {
    const drink = jest.fn();
    drinkAll(drink, 'lemon');
    expect(drink).toHaveBeenCalled();
  });

  test('does not drink something octopus-flavored', () => {
    const drink = jest.fn();
    drinkAll(drink, 'octopus');
    expect(drink).not.toHaveBeenCalled();
  });
});

.toHaveBeenCalledTimes(number) #

Use .toHaveBeenCalledTimes to ensure that a mock function got called exact number of times.

For example, let's say you have a drinkEach(drink, Array<flavor>) function that takes a drinkfunction and applies it to array of passed beverages. You might want to check that drink function was called exact number of times. You can do that with this test suite:

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']);
  expect(drink).toHaveBeenCalledTimes(2);
});

.toHaveBeenCalledWith(arg1, arg2, ...) #

Also under the alias: .toBeCalledWith()

Use .toHaveBeenCalledWith to ensure that a mock function was called with specific arguments.

For example, let's say that you can register a beverage with a register function, and applyToAll(f)should apply the function f to all registered beverages. To make sure this works, you could write:

test('registration applies correctly to orange La Croix', () => {
  const beverage = new LaCroix('orange');
  register(beverage);
  const f = jest.fn();
  applyToAll(f);
  expect(f).toHaveBeenCalledWith(beverage);
});

.toHaveBeenLastCalledWith(arg1, arg2, ...) #

Also under the alias: .lastCalledWith(arg1, arg2, ...)

If you have a mock function, you can use .toHaveBeenLastCalledWith to test what arguments it was last called with. For example, let's say you have a applyToAllFlavors(f) function that applies f to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is 'mango'. You can write:

test('applying to all flavors does mango last', () => {
  const drink = jest.fn();
  applyToAllFlavors(drink);
  expect(drink).toHaveBeenLastCalledWith('mango');
});

.toBeCloseTo(number, numDigits) #

Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. For example, this test fails:

test('adding works sanely with simple decimals', () => {
  expect(0.2 + 0.1).toBe(0.3); // Fails!
});

It fails because in JavaScript, 0.2 + 0.1 is actually 0.30000000000000004. Sorry.

Instead, use .toBeCloseTo. Use numDigits to control how many digits after the decimal point to check. For example, if you want to be sure that 0.2 + 0.1 is equal to 0.3 with a precision of 5 decimal digits, you can use this test:

test('adding works sanely with simple decimals', () => {
  expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});

The default for numDigits is 2, which has proved to be a good default in most cases.

.toBeDefined() #

Use .toBeDefined to check that a variable is not undefined. For example, if you just want to check that a function fetchNewFlavorIdea() returns something, you can write:

test('there is a new flavor idea', () => {
  expect(fetchNewFlavorIdea()).toBeDefined();
});

You could write expect(fetchNewFlavorIdea()).not.toBe(undefined), but it's better practice to avoid referring to undefined directly in your code.

.toBeFalsy() #

Use .toBeFalsy when you don't care what a value is, you just want to ensure a value is false in a boolean context. For example, let's say you have some application code that looks like:

drinkSomeLaCroix();
if (!getErrors()) {
  drinkMoreLaCroix();
}

You may not care what getErrors returns, specifically - it might return falsenull, or 0, and your code would still work. So if you want to test there are no errors after drinking some La Croix, you could write:

test('drinking La Croix does not lead to errors', () => {
  drinkSomeLaCroix();
  expect(getErrors()).toBeFalsy();
});

In JavaScript, there are six falsy values: false0''nullundefined, and NaN. Everything else is truthy.

.toBeGreaterThan(number) #

To compare floating point numbers, you can use toBeGreaterThan. For example, if you want to test that ouncesPerCan() returns a value of more than 10 ounces, write:

test('ounces per can is more than 10', () => {
  expect(ouncesPerCan()).toBeGreaterThan(10);
});

.toBeGreaterThanOrEqual(number) #

To compare floating point numbers, you can use toBeGreaterThanOrEqual. For example, if you want to test that ouncesPerCan() returns a value of at least 12 ounces, write:

test('ounces per can is at least 12', () => {
  expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
});

.toBeLessThan(number) #

To compare floating point numbers, you can use toBeLessThan. For example, if you want to test that ouncesPerCan() returns a value of less than 20 ounces, write:

test('ounces per can is less than 20', () => {
  expect(ouncesPerCan()).toBeLessThan(20);
});

.toBeLessThanOrEqual(number) #

To compare floating point numbers, you can use toBeLessThanOrEqual. For example, if you want to test that ouncesPerCan() returns a value of at most 12 ounces, write:

test('ounces per can is at most 12', () => {
  expect(ouncesPerCan()).toBeLessThanOrEqual(12);
});

.toBeInstanceOf(Class) #

Use .toBeInstanceOf(Class) to check that an object is an instance of a class. This matcher uses instanceof underneath.

class A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws

.toBeNull() #

.toBeNull() is the same as .toBe(null) but the error messages are a bit nicer. So use .toBeNull()when you want to check that something is null.

function bloop() {
  return null;
}

test('bloop returns null', () => {
  expect(bloop()).toBeNull();
});

.toBeTruthy() #

Use .toBeTruthy when you don't care what a value is, you just want to ensure a value is true in a boolean context. For example, let's say you have some application code that looks like:

drinkSomeLaCroix();
if (thirstInfo()) {
  drinkMoreLaCroix();
}

You may not care what thirstInfo returns, specifically - it might return true or a complex object, and your code would still work. So if you just want to test that thirstInfo will be truthy after drinking some La Croix, you could write:

test('drinking La Croix leads to having thirst info', () => {
  drinkSomeLaCroix();
  expect(thirstInfo()).toBeTruthy();
});

In JavaScript, there are six falsy values: false0''nullundefined, and NaN. Everything else is truthy.

.toBeUndefined() #

Use .toBeUndefined to check that a variable is undefined. For example, if you want to check that a function bestDrinkForFlavor(flavor) returns undefined for the 'octopus' flavor, because there is no good octopus-flavored drink:

test('the best drink for octopus flavor is undefined', () => {
  expect(bestDrinkForFlavor('octopus')).toBeUndefined();
});

You could write expect(bestDrinkForFlavor('octopus')).toBe(undefined), but it's better practice to avoid referring to undefined directly in your code.

.toContain(item) #

Use .toContain when you want to check that an item is in an array. For testing the items in the array, this uses ===, a strict equality check. .toContain can also check whether a string is a substring of another string.

For example, if getAllFlavors() returns an array of flavors and you want to be sure that lime is in there, you can write:

test('the flavor list contains lime', () => {
  expect(getAllFlavors()).toContain('lime');
});

.toContainEqual(item) #

Use .toContainEqual when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity.

describe('my beverage', () => {
  test('is delicious and not sour', () => {
    const myBeverage = {delicious: true, sour: false};
    expect(myBeverages()).toContainEqual(myBeverage);
  });
});

.toEqual(value) #

Use .toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass:

const can1 = {
  flavor: 'grapefruit',
  ounces: 12,
};
const can2 = {
  flavor: 'grapefruit',
  ounces: 12,
};

describe('the La Croix cans on my desk', () => {
  test('have all the same properties', () => {
    expect(can1).toEqual(can2);
  });
  test('are not the exact same can', () => {
    expect(can1).not.toBe(can2);
  });
});

Note: .toEqual won't perform a deep equality check for two errors. Only the message property of an Error is considered for equality. It is recommended to use the .toThrow matcher for testing against errors.

.toHaveLength(number) #

Use .toHaveLength to check that an object has a .length property and it is set to a certain numeric value.

This is especially useful for checking arrays or strings size.

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

.toMatch(regexpOrString) #

Use .toMatch to check that a string matches a regular expression.

For example, you might not know what exactly essayOnTheBestFlavor() returns, but you know it's a really long string, and the substring grapefruit should be in there somewhere. You can test this with:

describe('an essay on the best flavor', () => {
  test('mentions grapefruit', () => {
    expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
    expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
  });
});

This matcher also accepts a string, which it will try to match:

describe('grapefruits are healthy', () => {
  test('grapefruits are a fruit', () => {
    expect('grapefruits').toMatch('fruit');
  });
});

.toMatchObject(object) #

Use .toMatchObject to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are not in the expected object.

You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the toMatchObject sense described above) the corresponding object in the expected array. This is useful if you want to check that two arrays match in their number of elements, as opposed to arrayContaining, which allows for extra elements in the received array.

You can match properties against values or against matchers.

const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};
const desiredHouse = {
  bath: true,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    wallColor: expect.stringMatching(/white|yellow/),
  },
};

test('the house has my desired features', () => {
  expect(houseForSale).toMatchObject(desiredHouse);
});
describe('toMatchObject applied to arrays arrays', () => {
  test('the number of elements must match exactly', () => {
    expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
  });

  // .arrayContaining "matches a received array which contains elements that
  // are *not* in the expected array"
  test('.toMatchObject does not allow extra elements', () => {
    expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}]);
  });

  test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
    expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
      {foo: 'bar'},
      {baz: 1},
    ]);
  });
});

.toHaveProperty(keyPath, value) #

Use .toHaveProperty to check if property at provided reference keyPath exists for an object. For checking deeply nested properties in an object use dot notation for deep references.

Optionally, you can provide a value to check if it's equal to the value present at keyPath on the target object. This matcher uses 'deep equality' (like toEqual()) and recursively checks the equality of all fields.

The following example contains a houseForSale object with nested properties. We are using toHaveProperty to check for the existence and values of various properties in the object.

// Object containing house features to be tested
const houseForSale = {
  bath: true,
  bedrooms: 4,
  kitchen: {
    amenities: ['oven', 'stove', 'washer'],
    area: 20,
    wallColor: 'white',
  },
};

test('this house has my desired features', () => {
  // Simple Referencing
  expect(houseForSale).toHaveProperty('bath');
  expect(houseForSale).toHaveProperty('bedrooms', 4);

  expect(houseForSale).not.toHaveProperty('pool');

  // Deep referencing using dot notation
  expect(houseForSale).toHaveProperty('kitchen.area', 20);
  expect(houseForSale).toHaveProperty('kitchen.amenities', [
    'oven',
    'stove',
    'washer',
  ]);

  expect(houseForSale).not.toHaveProperty('kitchen.open');
});

.toMatchSnapshot(optionalString) #

This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.

You can also specify an optional snapshot name. Otherwise, the name is inferred from the test.

Note: While snapshot testing is most commonly used with React components, any serializable value can be used as a snapshot.

相關文章
相關標籤/搜索