It is strongly recommended that development be based on test-driven. Test-driven development can effectively precipitate development results and lock potential problems as soon as code changes occur, thus significantly improving the robustness of the code

On the basis of EggJS, CabloyJS provides a convenient framework for the development based on test-driven

Module test-party

When a new project is created, the module test-party is automatically downloaded to the directory where the project is located. Contains a large number of test-cases and kitchen-sink, and continues to add more content. It is not only convenient to quickly learn all aspects of knowledge points of CabloyJS, but also convenient to quickly start the actual business development

In this tutorial, the following tests are demonstrated. You can use this as an example to continuously expand test cases and increase code coverage as much as possible

  1. Login
  2. Create party
  3. Submit party (change status from draft to normal)
  4. Read party
  5. Delete party

Unit Test

src/module/test-party/backend/test/controller/test.test.js

const { app, mockUrl, mockInfo, assert } = require('egg-born-mock')(__dirname);

describe('action: atom: party', () => {
  it('[atom]', async () => {
    app.mockSession({});

    // atomClass info
    const atomClassModule = mockInfo().relativeName;
    const atomClassName = 'party';

    // login as root
    await app.httpRequest().post(mockUrl('/a/authsimple/passport/a-authsimple/authsimple')).send({
      auth: 'root',
      password: '123456',
    });

    // create
    let result = await app.httpRequest().post(mockUrl('/a/base/atom/create')).send({
      atomClass: { module: atomClassModule, atomClassName, atomClassIdParent: 0 },
    });
    assert(result.body.code === 0);
    const atomKey = result.body.data;

    // submit
    result = await app.httpRequest().post(mockUrl('/a/base/atom/submit')).send({
      key: atomKey,
      item: {
        atomName: 'party demo',
        personCount: 3,
      },
    });
    assert(result.body.code === 0);

    // read
    result = await app.httpRequest().post(mockUrl('/a/base/atom/read')).send({
      key: atomKey,
    });
    assert(result.body.code === 0);

    // delete
    result = await app.httpRequest().post(mockUrl('/a/base/atom/delete')).send({
      key: atomKey,
    });
    assert(result.body.code === 0);

  });
});
Name Description
mockUrl used to construct a complete backend API route
mockInfo used to obtain basic information about the module currently under test. For example, the current module name is test-party, but in order to improve the flexibility of the code, it can be obtained by mockInfo().relativeName
app.mockSession used to mock session environment

Run Test

$ npm run test:backend

Code Coverage

$ npm run cov:backend