前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Jest测试语法系列之Globals

Jest测试语法系列之Globals

作者头像
xiangzhihong
发布2022-11-30 14:55:31
1K0
发布2022-11-30 14:55:31
举报
文章被收录于专栏:向治洪

在上一篇文章中,我们主要介绍了Jest测试框架语法系列之Matchers的相关内容,本篇主要涉及的是Global Functions(全局函数),也是官方提供给开发者的核心功能之一。官方API地址为:https://jestjs.io/docs/en/api。

方法

  • afterAll(fn, timeout)
  • afterEach(fn, timeout)
  • beforeAll(fn, timeout)
  • beforeEach(fn, timeout)
  • describe(name, fn)
  • describe.each(table)(name, fn, timeout)
  • describe.only(name, fn)
  • describe.only.each(table)(name, fn)
  • describe.skip(name, fn)
  • describe.skip.each(table)(name, fn)
  • test(name, fn, timeout)
  • test.each(table)(name, fn, timeout)
  • test.only(name, fn, timeout)
  • test.only.each(table)(name, fn)
  • test.skip(name, fn)
  • test.skip.each(table)(name, fn)

Global

下面就列举Jest中常见的一些全局函数,欲知更多细节,请访问Jest官方文档

afterAll(fn, timeout)

此API的意思是,它是在所有测试运行完之后才会执行的,如果你的测试中包含promise,则将会等待promise被验证之后被执行。

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

如果想要清理一些跨测试共享的全局设置状态,afterAll也是有用的。

代码语言:javascript
复制
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在继续之前解决。

当然,你还可以提供一个超时(以毫秒为单位),用于指定在终止前等待的时间。afterEach默认的超时是5秒。

如果您想清除每个测试创建的临时状态,afterEach通常也是有用的。

代码语言:javascript
复制
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秒。

如果你想设置一些将被许多测试使用的全局状态,beforeAll通常也是有用的。

代码语言:javascript
复制
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在一个描述块中,它在描述块的开始处运行。 如果你想在每次测试之前运行一些东西,而不是在任何测试之前运行,那么请在每个测试之前使用。

beforeEach(fn, timeout)

在该文件运行的每个测试之前运行一个函数,如果函数返回一个promise,Jest将等待该承诺在运行测试之前解决。

你还可以提供一个超时(以毫秒为单位),用于指定在终止前等待的时间,默认的超时是5秒。

如果你想要重置一些将被许多测试所使用的全局状态,beforeEach通常也是有用的。

代码语言:javascript
复制
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)创建一个块,在一个“测试套件”中,将几个相关的测试组合在一起。

代码语言:javascript
复制
const myBeverage = {
  delicious: true,
  sour: false,
};

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

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

当然,这不是必需的。你可以直接在顶层编写测试块,但是,如果您希望将测试组织成组,那么这就很方便,且利于查看和维护。

代码语言:javascript
复制
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)

如果你只想运行一次模块测试的话,可以使用 describe.only。

代码语言:javascript
复制
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 跳过某一个测试。

代码语言:javascript
复制
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
});

使用跳过通常只是一种比较简单的替代方法,如果不想运行则可以暂时将大量的测试注释掉。

test(name, fn, timeout)

test(name, fn, timeout) 等价于 it(name, fn, timeout)。在测试文件中,您所需要的是运行测试的测试方法。例如,假设有一个函数inchesOfRain()应该是零。

代码语言:javascript
复制
test('did not rain', () => {
  expect(inchesOfRain()).toBe(0);
});

其中,第一个参数是测试名称,第二个参数是包含测试期望的函数,第三个参数(可选)是超时(以毫秒为单位),用于指定在中止前等待多长时间,默认的超时是5秒。

如果测试返回了一个promise,Jest会在测试完成之前等待promise。Jest还将等待,如果你为测试函数提供一个参数,通常称为done。当你想要测试回调时,这将非常方便。请参见如何在此测试异步代码。

例如,假设fetchBeverageList()返回一个承诺,该承诺将解析到其中有lemon的列表。

代码语言:javascript
复制
test('has lemon in it', () => {
  return fetchBeverageList().then(list => {
    expect(list).toContain('lemon');
  });
});

在上面的测试例子中,即使对测试的调用会立即返回,测试也不会完成,直到promise解决。

test.only(name, fn, timeout)

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

在调试大型代码库时,有时候你只希望运行一个子集的测试。 test.only可以指定哪些测试是您想要运行的。

当然,您还可以提供一个超时(以毫秒为单位),用于指定在终止前等待的时间。默认的超时是5秒。

代码语言:javascript
复制
test.only('it is raining', () => {
  expect(inchesOfRain()).toBeGreaterThan(0);
});

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

test.skip(name, fn)

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

当您维护一个大型的代码库时,您可能有时会发现由于某种原因而临时中断的测试。

如果您想跳过这个测试,但是您不想仅仅删除这个代码,您可以使用skip指定一些测试来跳过。

代码语言:javascript
复制
test('it is raining', () => {
  expect(inchesOfRain()).toBeGreaterThan(0);
});

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

test.skip.each(table)(name, fn)

如果您想停止运行数据驱动测试的集合。test.skip是很适合的,每个都有两个api。

代码语言:javascript
复制
test.skip.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])(
  '.add(%i, %i)',
  (a, b, expected) => {
    expect(a + b).toBe(expected); // will not be ran
  },
);

test('will be ran', () => {
  expect(1 / 0).toBe(Infinity);
});
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-11-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方法
  • Global
    • afterAll(fn, timeout)
      • afterEach(fn, timeout)
        • beforeAll(fn, timeout)
          • beforeEach(fn, timeout)
            • describe(name, fn)
              • describe.only(name, fn)
                • describe.skip(name, fn)
                  • test(name, fn, timeout)
                    • test.only(name, fn, timeout)
                      • test.skip(name, fn)
                        • test.skip.each(table)(name, fn)
                        领券
                        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档