0%

2. Unit Testing

Testing

not in the production, just for element checking before a deployment

Automated Tests
반복되는 test 작업을 줄임

  1. Unit
    receives a single case input, return certain type of output
    wouldn’t pass unless the entire process works out
    e.g. validation email & password -> similar word -> set the function as a unit with diff. input

  2. Integration
    multiple single inputs -> integrates into a single output
    e.g. email / pw -> basic email : password

  3. E2E
    end-to-end
    user-perspective, operation on the browser, entire process without manually fixing it
    hard to point where the error comes out


TDD

Test Driven Development
fail-fix-refactor

  • one test at a time

BDD

Bahaviour Driven Development
E2E

  • testing single unit, element to test entirely
  • implemented in non-technical env. -> no coding

diff: technical or not


Testing Frameworks: the function to run the tests (in JS - Mocha, Jasmine(React), Jest)

# : e.g. #func() : recall all the elements including func()

  • describe()
  • it()
  • Hooks; rather than list singly, wrap it for organizing
    • start a server, create DB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
describe('hooks', function() {
before(function() {
// runs once before the first test in this block
});

after(function() {
// runs once after the last test in this block
});

beforeEach(function() {
// runs before each test in this block
});

afterEach(function() {
// runs after each test in this block
});

// test cases
});

inside each hooks: it()


Assertion

  1. assert -> technical, not readable

    • built-in in Node.js
    • typeOf(var, typeof, [msg])
    • equal(var, val, [msg])
    • lengthOf(var, length, [msg])
  2. expect
    e.g. expect(foo).to.not.equal('bar')

  3. should
    e.g. foo.should.not.equal('bar')

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function add (a, b) {
if (typeof a === 'number' && b === undefined) return a;
if (typeof a !== 'number' || typeof b !== 'number') return undefined;
// return 8;
return a + b;
}

// write the test first
var should = require('chai').should();

describe('Add', function () {
it('should sum two numbers', function () {
add(3, 5).should.equal(8);
// add another ex to fail add(a,b) {return 8;} function
add(2, 7).should.equal(9);
});

it('should return undefined when is not passed numbers', function () {
should.equal(add('hello', 'world'), undefined);
// add('').should.equal이 아닌 이유:
// undefined을 반환하면 undefined.should.equal()이 되고,
// 이는 error(cannot read the property)를 반환 (undefined의 function 정의 불가)
// 따라서 should.equal(add(''))의 결과와 undefined를 matching

should.equal(add(1, 'world'), undefined);
should.equal(add('hello', 1), undefined);
});

it('should return the number if only one is passed', function () {
should.equal(add(8), 8);
// add(8).should.equal(8);
});
});

REF

kent c.dodds web
mochajs.com