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 codes

On the basis of EggJS, EggBornJS 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

API Route: version/test

Before the test cases are executed, the backend API route version/test of each module will be executed automatically

At this stage, you can prepare some test data for testing (such as role, user, permission, etc.)

Take the module test-party as an example, add the following test data:

  1. Add user demo001
  2. Add user’s login authentication information
  3. Append user demo001 to role registered

src/module/test-party/backend/src/service/version.js

async test() {
  // create test users: demo001
  const users = [
    { userName: 'demo001', roleName: 'registered' },
  ];
  const userIds = [];
  for (const user of users) {
    // add user
    userIds[user.userName] = await this.ctx.meta.user.add({
      userName: user.userName,
      realName: user.userName,
    });
    // add auth info for login
    await this.ctx.performAction({
      method: 'post',
      url: '/a/authsimple/auth/add',
      body: {
        userId: userIds[user.userName],
        password: '123456',
      },
    });
    // role
    const role = await this.ctx.meta.role.get({ roleName: user.roleName });
    // add user role
    await this.ctx.meta.role.addUserRole({
      userId: userIds[user.userName],
      roleId: role.id,
    });
  }
}

app.meta.isTest, app.meta.isLocal

The corresponding codes can be loaded in the specified environment through app.meta.isTest or app.meta.isLocal

For example, the resources in the module test-party can only take effect in the test environment and development environment, but not in the production environment. You can operate as follows:

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

const party = require('./model/party.js');
const partyType = require('./model/partyType.js');
const partyPublic = require('./model/partyPublic.js');

module.exports = app => {
  const models = {
  };
  if (app.meta.isTest || app.meta.isLocal) {
    Object.assign(models, {
      party,
      partyType,
      partyPublic,
    });
  }
  return models;
};