Test-Driven Development

2018-12-09 13:47:49

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, Cabloy provides a convenient framework for the development based on test-driven

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 todo
  3. Submit todo (change status from draft to normal)
  4. Read todo
  5. Delete todo

Unit Test


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

describe('[your tests start from here]', () => {
  it('[atom]', async () => {

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

    // 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: 'test',
        description: 'this is a test',
    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-todo, 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