Skip to content

Latest commit

 

History

History
153 lines (114 loc) · 2.45 KB

16-testing.md

File metadata and controls

153 lines (114 loc) · 2.45 KB

Testing

Test Pyramid

Test Pyramid

Test Types

Test Types

Examples

Integration Tests Negative Tests Promises Tests

Arrange Act Assert

  • Structural pattern to test requirements
// Arrange
const sut = 'ABC';
// Act
const actual = sut.split('').reverse();
// Assert
assert.deepEqual(actual, ['C', 'B', 'A']);

Mocha

npm install mocha --save-dev

package.json

"scripts": {
	"test": "mocha --watch ./tests"
}
const assert = require('assert');

describe('Group 1', () => {
  it('test 1', () => {
    assert.equal(1, 2);
  });
});

Asserts

assert.equal(actual, expected);

const assert = require('assert');

assert(true);
// OK
assert(1);
// OK
assert(false);
// throws "AssertionError: false == true"
assert(0);
// throws "AssertionError: 0 == true"
assert(false, "it's false");
// throws "AssertionError: it's false"

Assert-Plus

Negative Tests

  • Test errors
  • Test the right error
const assert = require('assert');

function thatThrowAnError() {
  throw new Error('my error');
}

describe('Group 1', () => {
  it('test 1 should throw', () => {
    assert.throws(thatThrowAnError, Error);
  });
});

Async Tests

Callbacks

const assert = require('assert');

describe('Group 1', function() {
  this.timeout(4000);

  it('test 1', done => {
    setTimeout(() => {
      assert.equal(1, 2);
      done();
    }, 3000);
  });
});

Promises

const assert = require('assert');

function asPromise() {
  return new Promise(resolve => {
    setTimeout(() => resolve(2), 3000);
  });
}

describe('Group 1', function() {
  this.timeout(4000);

  it('test 1', () => {
    return asPromise().then(actual => {
      assert.equal(actual, 2);
    });
  });
});

Integration Tests

  • Testing more than functions
  • Prepare environment(s)
    • Use module exports/require
    • before, after
    • beforeEach, afterEach
  • Multiple asserts

Example