redux source code interpretation (2)

Posted by holowugz on Sun, 03 May 2020 19:17:48 +0200

(1) A simple version of redux is written in. The tests are all directly based on the command line output. Obviously, this is unscientific

So you need to write tests, so. I chose jest.

The introduction on the Internet is as follows .

Configure simple test environment according to official documents

npm install --save-dev jest

Add the following to package.json

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

Add babel support to support the latest es syntax

npm install babel-preset-env --save-dev
//.babelrc
{
    "presets": ["env"]
  }

At this time, when npm run test is run on the terminal, jest will automatically run every xxx.test.js and xxx.spec.js under the project directory

Several simple test samples are written in combination with the previous simple store

const createStore = require('../src/createStore');
const {testReducer} = require('./testdata');
describe('test createStore', () => {
    it('test store Function interface of instance', () => {
        const store = createStore(testReducer);
        const methods = Object.keys(store)
        expect(methods.length).toBe(4)
        expect(methods).toContain('subscribe')
        expect(methods).toContain('dispatch')
        expect(methods).toContain('getState')
        expect(methods).toContain('replaceReducer')
    });
    it('test state Initial value', () => {
        const store = createStore(testReducer, {sum: 520});
        expect(store.getState()).toEqual({sum: 520})
    });
    it('test dispatch', () => {
        const store = createStore(testReducer, {sum: 0});
        expect(store.getState()).toEqual({sum: 0});

        //add one-tenth
        store.dispatch({type: 'ADD'});
        expect(store.getState()).toEqual({sum: 1});
        //Minus one
        store.dispatch({type: 'DEC'});
        expect(store.getState()).toEqual({sum: 0});
    })
})


It can be seen that several samples of the test have been successful. If the error is reported, for example, write the expected value of the initial value as - 1
expect(store.getState()).toEqual({sum: -1});
It's going to be a false report. It's going to show

Farewell to the time of human flesh console test hhhh

Topics: npm JSON