前端測試框架Jest系列教程 -- Global Functions(全局函數)


寫在前面:

  Jest中定義了很多全局性的Function供我們使用,我們不必再去引用別的包來去實現類似的功能,下面將列舉Jest中實現的全局函數。

Jest Global Functions

afterAll(fn, timeout)

從字面意思就可以理解到它是在所有測試運行完之后才會執行的,如果你的測試中包含promise,則將會等待promise被驗證之后被執行。

你還可以提供一個timeout的參數(以毫秒為單位),用於指定在終止前等待的時間。注意:默認的超時是5秒。

如果您想要清理一些跨測試共享的全局設置狀態,這通常是有用的。

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

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

在這里,afterAll確保在所有測試運行后調用cleanUpDatabase。

如果在描述塊內部,它在描述塊的末尾運行。

如果你想在每次測試之后運行一些清理,而不是在所有測試之后,使用afterEach代替。

afterEach(fn, timeout)

在該文件中的每一個測試完成后運行一個函數。如果函數返回一個promise,Jest會等待該promise在繼續之前解決。

你還可以提供一個超時(以毫秒為單位),用於指定在終止前等待的時間。注意:默認的超時是5秒。

如果您想清除每個測試創建的臨時狀態,這通常是有用的。

const globalDatabase = makeGlobalDatabase();

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

afterEach(() => {
  cleanUpDatabase(globalDatabase);
});

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

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

在這里,afterEach確保在每次測試運行后調用cleanUpDatabase。

如果每個都在一個描述塊內,它只在這個描述塊內的測試之后運行。

如果你只想在運行完所有測試之后運行一些清理工作,那么使用afterAll代替。

beforeAll(fn, timeout)

在該文件運行的任何測試之前運行一個函數。如果函數返回一個承諾,則Jest會等待在運行測試之前解決這個問題。

你還可以提供一個超時(以毫秒為單位),用於指定在終止前等待的時間。注意:默認的超時是5秒。

如果你想設置一些將被許多測試使用的全局狀態,這通常是有用的。

const globalDatabase = makeGlobalDatabase();

beforeAll(() => {
  // Clears the database and adds some testing data.
  // Jest will wait for this promise to resolve before running tests.
  return globalDatabase.clear().then(() => {
    return globalDatabase.insert({testData: 'foo'});
  });
});

// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

在這里,beforeAll確保在測試運行之前建立數據庫。

如果設置是同步的,那么你可以在沒有以前的情況下這樣做。關鍵是Jest將等待一個promise來解決,因此你也可以擁有異步設置。

如果beforeAll在一個描述塊中,它在描述塊的開始處運行。 如果你想在每次測試之前運行一些東西,而不是在任何測試之前運行,那么請在每個測試之前使用。

beforeEach(fn, timeout)

在該文件運行的每個測試之前運行一個函數。如果函數返回一個promise,Jest將等待該承諾在運行測試之前解決。

你還可以提供一個超時(以毫秒為單位),用於指定在終止前等待的時間。注意:默認的超時是5秒。

如果你想要重置一些將被許多測試所使用的全局狀態,這通常是有用的。

const globalDatabase = makeGlobalDatabase();

beforeEach(() => {
  // Clears the database and adds some testing data.
  // Jest will wait for this promise to resolve before running tests.
  return globalDatabase.clear().then(() => {
    return globalDatabase.insert({testData: 'foo'});
  });
});

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

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

在此之前,每個測試都要重置數據庫。

如果在一個描述塊內部,它運行在描述塊中的每個測試。

如果你只需要運行一些設置代碼,在任何測試運行之前,就使用之前的所有代碼。

describe(name, fn)

describe(name, fn)創建一個塊,在一個“測試套件”中,將幾個相關的測試組合在一起。

const myBeverage = {
  delicious: true,
  sour: false,
};

describe('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

這不是必需的——你可以直接在頂層編寫測試塊。但是,如果您希望將測試組織成組,那么這就很方便了。

const binaryStringToNumber = binString => {
  if (!/^[01]+$/.test(binString)) {
    throw new CustomError('Not a binary number.');
  }

  return parseInt(binString, 2);
};

describe('binaryStringToNumber', () => {
  describe('given an invalid binary string', () => {
    test('composed of non-numbers throws CustomError', () => {
      expect(() => binaryStringToNumber('abc')).toThrowError(CustomError);
    });

    test('with extra whitespace throws CustomError', () => {
      expect(() => binaryStringToNumber('  100')).toThrowError(CustomError);
    });
  });

  describe('given a valid binary string', () => {
    test('returns the correct number', () => {
      expect(binaryStringToNumber('100')).toBe(4);
    });
  });
});

describe.only(name, fn)

如果你只想運行一次模塊測試的話你可以使用 only

describe.only('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

describe('my other beverage', () => {
  // ... will be skipped
});

describe.skip(name, fn) describe 等價於 xdescribe

你可以使用skip 跳過某一個測試

describe('my beverage', () => {
  test('is delicious', () => {
    expect(myBeverage.delicious).toBeTruthy();
  });

  test('is not sour', () => {
    expect(myBeverage.sour).toBeFalsy();
  });
});

describe.skip('my other beverage', () => {
  // ... will be skipped
});

使用跳過通常只是一種比較簡單的替代方法,如果不想運行則可以暫時將大量的測試注釋掉。

require.requireActual(moduleName)

返回實際的模塊而不是模擬,繞過所有檢查模塊是否應該接收模擬實現。

require.requireMock(moduleName)

返回一個模擬模塊,而不是實際的模塊,繞過所有檢查模塊是否正常。

test(name, fn, timeout) 等價於 it(name, fn, timeout)

在測試文件中,您所需要的是運行測試的測試方法。例如,假設有一個函數inchesOfRain()應該是零。你的整個測試可以是:

test('did not rain', () => {
  expect(inchesOfRain()).toBe(0);
});

第一個參數是測試名稱;第二個參數是包含測試期望的函數。第三個參數(可選)是超時(以毫秒為單位),用於指定在中止前等待多長時間。注意:默認的超時是5秒。

注意:如果測試返回了一個promise,Jest會在測試完成之前等待promise。Jest還將等待,如果你為測試函數提供一個參數,通常稱為done。當你想要測試回調時,這將非常方便。請參見如何在此測試異步代碼。

例如,假設fetchBeverageList()返回一個承諾,該承諾將解析到其中有lemon的列表。你可以用:

test('has lemon in it', () => {
  return fetchBeverageList().then(list => {
    expect(list).toContain('lemon');
  });
});

即使對測試的調用會立即返回,測試也不會完成,直到promise解決。

test.only(name, fn, timeout)等同於 it.only(name, fn, timeout) or fit(name, fn, timeout)

在調試大型代碼庫時,通常只希望運行一個子集的測試。您可以使用。只指定哪些測試是您想要運行的。

您還可以提供一個超時(以毫秒為單位),用於指定在終止前等待的時間。注意:默認的超時是5秒。

test.only('it is raining', () => {
  expect(inchesOfRain()).toBeGreaterThan(0);
});

test('it is not snowing', () => {
  expect(inchesOfSnow()).toBe(0);
});

只有“it is raining”測試才會運行,因為它是用test運行的。

通常你不會使用測試來檢查代碼。只有在源代碼控制中——您將僅用於調試,並在修復了故障測試后刪除它。

test.skip(name, fn)等同於it.skip(name, fn) or xit(name, fn) or xtest(name, fn)

當您維護一個大型的代碼庫時,您可能有時會發現由於某種原因而臨時中斷的測試。

如果您想跳過這個測試,但是您不想僅僅刪除這個代碼,您可以使用skip指定一些測試來跳過。

test('it is raining', () => {
  expect(inchesOfRain()).toBeGreaterThan(0);
});

test.skip('it is not snowing', () => {
  expect(inchesOfSnow()).toBe(0);
});

只有“it is raining”測試運行,因為另一個測試運行test . skip。 您可以簡單地對測試進行注釋,但是使用skip會更好一些,因為它將保持縮進和語法突出。

寫在最后:

  本文介紹了一些Jest中的全局函數,可以在任意地方方便的使用。 

系列教程:

   1. 前端測試框架Jest系列教程 -- Matchers(匹配器)

   2.前端測試框架Jest系列教程 -- Asynchronous(測試異步代碼)

   3.前端測試框架Jest系列教程 -- Mock Functions(模擬器)

   4.前端測試框架Jest系列教程 -- Global Functions(全局函數)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM