Front end unit test 03 Sion

Front end unit test 03 Sion

  • Problems in front-end test
    Before talking about Sinon, we have to talk about some problems in our front-end testing after learning Mocha, chai and enzyme.
    For example, the foreground test needs to interact with the background, and then test according to the corresponding data after obtaining the background data.
    For example, we can test the other function separately according to the decoupled function.
  • Test aid Sinon
    Sinon is used to assist us in front-end testing. When our code needs to interface with other systems or functions, it can simulate these scenarios, so that we can no longer rely on these scenarios during testing.
    Sinon has three main methods to assist us in testing: spy, stub and mock.
  • Installation of Sion
npm install --save-dev sinon

Official demo:

export default function once(fn) {
    var returnValue, called = false;
    return function () {
        if (!called) {
            called = true;
            returnValue = fn.apply(this, arguments);
        }
        return returnValue;
    };
}
  • spy of Sinon
    Spy generates a spy function, which records the parameters of the function call, the return value, the value of this, and the exceptions thrown.
    Spy generally has two ways to play. One is to generate a new anonymous spy function, and the other is to encapsulate and monitor the original function.
    After setting up the above structure, directly in once test. Example of writing spy in JS:

    import {assert} from 'chai'
    import sinon from 'sinon'
    import once from '../src/once'
    
    describe('test Once function', function () {
      it('afferent Once The function will be called', function () {
        var callback = sinon.spy();
        var proxy = once(callback);
    
        proxy();
    
        assert(callback.called);
      });
    })
    

    As shown in the above code, Sino Spy () will generate a function object. When once calls this function object, the function object can return a bool value through called, indicating whether the function is called or not.
    Now let's take a look at another play of spy, that is, the monitoring play of the original function, in once test. Add the following test cases to JS:

	it('Of original function spy Encapsulation, which can monitor the call of the original function', function () {
    const obj={
        func:()=>{
            return 1+1
        }
    }
    sinon.spy(obj,'func')

    obj.func(3);

    assert(obj.func.calledOnce)
    assert.equal(obj.func.getCall(0).args[0], 3);
});
  • Sinon's Stub
    Let's take a look at the official introduction of Stub:

Test stubs are functions (spies) with pre-programmed behavior. They support the full test spy API in addition to methods which can be used to alter the stub's behavior. As spies, stubs can be either anonymous, or wrap existing functions. When wrapping an existing function with a stub, the original function is not called.

stub is a function with pre programmed behavior.
Simply put, it is an enhanced version of spy, which not only fully supports various operations of spy, but also operates the behavior of functions.
Like spy, stub can also be anonymous and can seal and listen to existing functions.
However, unlike spy, when an existing function is encapsulated, the original function will not be called again.

We won't talk about the anonymous play method. We will directly encapsulate the play method. The following are the modifications to the previous spy encapsulation:

it('Of original function stub Encapsulation, which can monitor the call of the original function,And simulated return', function () {
    const obj={
        func:()=>{
           console.info(1)
        }
    }
    sinon.stub(obj,'func').returns(42)

    const result=obj.func(3);

    assert(obj.func.calledOnce)
    assert.equal(obj.func.getCall(0).args[0], 3);
    assert.equal(result,43);
});

More API views Sinon's stub

  • mock of Sinon
    Take a look at the introduction on the official website

    Mocks (and mock expectations) are fake methods (like spies) with pre-programmed behavior (like stubs) as well as pre-programmed expectations.
    A mock will fail your test if it is not used as expected.

    it('mock Test of', function () {
        var myAPI = { 
            method: function () {
                console.info("function method")
            },
            func: function () {
                console.info("function method")
            }
        };
    
        var mock = sinon.mock(myAPI);
        mock.expects("method").once().returns(2);
        mock.expects("func").twice()
    
        myAPI.method();
        myAPI.func();
        myAPI.func();
    
        mock.verify();
    });
    

    In the above code, mock is actually very similar to stub, except that stub listens and intercepts a single function in an object, while mock listens to multiple functions.
    mock first expects the function:

    var mock = sinon.mock(myAPI);
       mock.expects("method").once().returns(2);
       mock.expects("func").twice()
    

    For example, once is expected to run once. If the function is not executed or executed multiple times during final verification, an error will be thrown.
    You can also manipulate the return result. For example, like stub, returns(2) is still valid.
    Moreover, like stub, after mock listening, the original function content will not be executed.

    After the expected operation is performed, the function is actually operated:

    myAPI.method();
    myAPI.func();
    myAPI.func();
    

    Finally, verify:

    mock.verify();
    

summary

Sinon is mainly a test assistant tool, which simulates the operation with other systems or functions through camouflage and interception, and can decouple the dependence of the test.
Only the spy, stub and mock functions of Sinon are mentioned above. In fact, there are also make xhr (simulated xhr request), fack server (simulated server) and make timer (simulated timer). I won't talk about it here. For details, you can view this API: Sinon v4.1.6.

Keywords: Front-end unit testing

Added by dancing dragon on Wed, 05 Jan 2022 16:51:03 +0200