Using Jest for javacript Unit Test 使用jest进行单元测试

1. What is jest

Jest is produced by facebook as a code testing frame. It has implemented with functions of Mocha,chai,jsdomandsinon, and you can know more about jest through Starter and GitHub.

2. How to start

After installed jest:

npm install --save-dev jest 

And run npm run jest, then jest will print messages as:

PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

Jest by default it will auto to check all the file in your project which contains the suffix as .test.js or .spect.js(also .ts). More config can be seen and set in the package.json file. For example:

{
  "scripts": {
    "test": "jest"  //npm run test
  },
  "jset": {
    "testRegex": "/test/.*.spec.ts$"  //following the rules of regular matching 
  }
}

Jest only try to run test in the files in tess folder with .spec.ts suffix.

3. How to use

The core function of jest is the Mathcers.

expect(funciton()).matchers(expect_result)
expect(funciton()).not.matchers(expect_result)

This document just gives the list of matchers(Jest_v24.9) and for proper use please checking in the guide url.

(1) Common Matchers

The simplest way to test a value is with exact equality.

  • tobe uses Object.is to test exact equality;
  • toEqual check the value of an object if equal to expected value;

(2) Truthiness

In tests you sometimes need to distinguish between undefined, null, and false, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.

  • toBeNull matches only null
  • toBeUndefined matches only undefined
  • toBeDefined is the opposite of toBeUndefined
  • toBeTruthy matches anything that an if statement treats as true
  • toBeFalsy matches anything that an if statement treats as false

(3) Numbers

Most ways of comparing numbers have matcher equivalents.

  • toBeGreaterThan matches result > expected
  • toBeGreaterThanOrEqual matches result >= expected
  • toBeLessThan matches result < expected
  • toBeLessThanOrEqual matches result <= expected

(4) Strings

You can check strings against regular expressions with toMatch due to the regular matching rules:

expect('Christoph').toMatch(/stop/);
expect('team').not.toMatch(/I/);

(5) Arrays and Iterables

You can check if an array or iterable contains a particular item using toContain:

expect(sampleArray).toContain('test');

(6) Exceptions

This is just a taste. For a complete list of matchers, check out the reference docs.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。