前端测试框架Jest系列教程 -- Global Functions(全局函数)

写在前面:

  Jest中定义了不少全局性的Function供咱们使用,咱们没必要再去引用别的包来去实现相似的功能,下面将列举Jest中实现的全局函数。html

Jest Global Functions

afterAll(fn, timeout)前端

从字面意思就能够理解到它是在全部测试运行完以后才会执行的,若是你的测试中包含promise,则将会等待promise被验证以后被执行。数据库

你还能够提供一个timeout的参数(以毫秒为单位),用于指定在终止前等待的时间。注意:默认的超时是5秒。promise

若是您想要清理一些跨测试共享的全局设置状态,这一般是有用的。框架

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)fetch

在该文件中的每个测试完成后运行一个函数。若是函数返回一个promise,Jest会等待该promise在继续以前解决。ui

你还能够提供一个超时(以毫秒为单位),用于指定在终止前等待的时间。注意:默认的超时是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(全局函数)

相关文章
相关标签/搜索