Javascript Unit Test Tool-Jest Learning Notes (1)

Keywords: npm JDK Javascript less

Write before

First of all, this is not a complete tutorial on Jest. It is just a little casual notes that one takes when he comes to Jest. Most of the content is translated into some official documents.Just let people who want to know jest know quickly what jest does and how to do it.For how to test the project, especially React, which is currently very popular, you will need to be familiar with it later or write another piece of experience.

What's Jest

Jest It's a unit-testing tool for javascript that Facebook developed, was previously used only internally, was later open-source, and evolved from the Jasmine testing framework using the assertion format we're familiar with expect(value).toBe(other).

Getting Start

First Jest Test Demo

Install via npm

$ npm install jest --save-dev

Edit a sum.js file to be tested as follows:

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

Edit a test file sum.test.js

Note: For the location of this test file, it is recommended that a new u test_u folder be created for each component, and the file name is name.test.js, which is used to store the test file.

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

Next, add test commands to the package.json file

"scripts:" {
    "test": "jest"
}

Finally, after running the npm test command, jest will print the following information

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

At this point, the first test Demo is complete.

Using Matchers

Jest uses matchers to test your results in different ways.

Common Matchers

The easiest way to test is to test if a value is equal

test('2 Add 2 equals 4', ()=> {
    expect(2 + 2).toBe(4);
});

In the above code, expect(2+2) returns an "expected" object, which is usually not matched by a matcher, which is here. toBe(4) is the matcher, and when Jest runs, it tracks all failed matchers to print the correct error information to us.

ToBeuses == to test for all equals. If we want to check the value in an object, toEqual instead, toEqual recursively iterates through every field in an object or array.

"use strict";
    
test('object assigenment', ()=> {
    let data = { one: 1};
    data['two'] = 2;
    expect(data).toEqual({ one: 1, two: 2 });
})

Note: An example of an official website is an unused "use strict"; then an error will be reported when npm test
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

Using not s, you can test the reverse rule of a matchers:

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

Truthiness

Sometimes when testing, we need to differentiate undefined, null and false, but we don't want to know their differences, and Jest helps us get the results we want.

  • toBeNull check if it is null

  • toBeUndefined checks if undefined

  • The opposite of toBeDefined and toBeUndefined

  • toBeTruthy checks whether any conversion through if display is true

  • toBeFalsy checks if any conversion through if display is false

The following:

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

test('zero', () => {
      let z = 0;
      expect(z).not.toBeNull();
      expect(z).toBeDefined();
      expect(z).not.toBeUndefined();
      expect(z).not.toBeTruthy();
      expect(z).toBeFalsy();
});

Numbers

Most methods of comparing numbers have their matchers

  • toBeGreaterThan is greater than

  • toBeGreaterThanOrEqual greater than or equal to

  • toBeLessThan is less than

  • toBeLessThanOrEqual is less than or equal to

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

    // toBe and toEqual work the same for number Type
    expect(value).toBe(4);
    expect(value).toEqual(4);
});

For floating point tests, toBeCloseTo is used instead of toEqual, because we don't make a test dependent on a minor rounding error.

test('adding floating point numbers', () => {
    let value = 0.1 + 0.2;
    expect(value).not.toBe(0.3);    // It isn't! Because rounding error
    expect(value).toBeCloseTo(0.3); // This works.
});

Strings

Regular expression matching of strings using 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/);
})

Arrays

Use toContain to match specific items within an array

let shoppingList = ['diapers', 'kleenex', 'trash bags', 'paper towels', 'beer'];

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

Exceptions

Use toThrow to test errors thrown during a specific function call

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

Testing Asynchronous Code

In javascript programs, you often see code that executes asynchronously. When we have code that executes asynchronously, Jest needs to know if the current code test is complete before moving on to another test.Jest provides some ways to deal with this problem.

Callbacks

The most common asynchronous test pattern is callbacks

For example, we have a fetchData(callback) method, when the callback(data) method is called, we get some data data and want to test if the returned data is just a string uyun.

By default, Jest completes tests after all the code has been executed, which means they will no longer work as planned.

// Don't do this!
test('the data is uyun', () => {
    function callback(data) {
        expect(data).toBe('uyun');
    }

    fetchData(callback);
});

The problem is that the test expects fatchData to complete once it succeeds and callbacks to be invoked before it.

There is another way to fix the problem with this test, in which a callback parameter with a parameter of done is used instead of placing an empty parameter, and Jest will not end the test until done is called.

test('the data is uyun', done => {
    function callback(data) {
        expect(data).toBe('uyun');
        done();
    }

    fetchData(callback);
});

If done() is not called, the test fails, and we get the wrong results we want.

Promises

If Promises is used in our code, here is a simple asynchronous test handling method.Just a promise is returned in our test, and Jest waits for the promise resolution to complete, and if rejected, the test is automatically considered a failure.The following:

test('the data is uyun', () => {
    return fetchData().then(data => {
        expect(data).toBe('uyun');
    });
});

Note: Be sure to return to Promise. If you omit this step, your test will end before fetchData finishes.

Async/Await

If you use async and await in your code, you can do so.Write an asynchronous test by using the async keyword before the test method and passing it to the test function.The following:

test('the data is uyun', async () => {
    const data = await fetchData();
    expect(data).toBe('uyun');
});

In this example, async and await are equivalent to a syntax sugar implementation of the promises method.

Posted by []InTeR[] on Fri, 10 May 2019 03:30:39 -0700