Napisanie testu jednostkowego

0

Czy może ktoś podpowiedzieć na czym polega test jednostkowy? I jak napisać go do takiego kodu w JS ?

var max = 0;
var num;
var customModuleRe = new RegExp('\\d+');
var activeModules = [
    { name: 'module 1' },
    { name: 'module 2' },
    { name: 'module 3' },
    { name: 'module 10' },
    { name: 'module 11' }
];

(function getCustomModuleNumber() {
    for (var i = 0; i < activeModules.length; i++) {
        if (customModuleRe.exec(activeModules[i].name)) {
             num = parseInt(customModuleRe.exec(activeModules[i].name));
            if (num > max) {
                max = num;
            }
        }
    }
    return max;
})();
0

Nie da się napisać testu do tego kodu - funkcja getCustomModuleNumber jest niewidoczna dla reszty kodu, operujesz na zmiennych globalnych. Trochę zgadując co ten kod ma robić (i zakładając, że globale są uzywane tylko tutaj):

  • kod modułu:
const MODULE_NUMBER_REGEX = new RegExp('\\d+')

function getCustomModulesMaxNumber(activeModules) {
    var max = 0;
    var num;
    for (var i = 0; i < activeModules.length; i++) {
      if (MODULE_NUMBER_REGEX.exec(activeModules[i].name)) {
        num = parseInt(MODULE_NUMBER_REGEX.exec(activeModules[i].name))
        if (num > max) {
          max = num
        }
      }
    }
    return max
}

export default getCustomModulesMaxNumber
  • kod testu (używam Mocha + Chai bo najpopularniejsze):
import { expect } from chai
import getCustomModulesMaxNumber from 'path/to/module'

describe('getCustomModulesMaxNumber', () => {
  it('returns 0 if there are no custom modules', () => {
    const input = []
    const expected = 0
    const actual = getCustomModulesMaxNumber(input)
    
    expect(actual).to.equal(expected)
  })
  
  it('returns biggest module number', () => {
    const input = [
      { name: 'module 10' },
      { name: 'module 2' },
      { name: 'module 22' },
      { name: 'module 13' },
    ]
    const expected = 22
    const actual = getCustomModulesMaxNumber(input)
    
    expect(actual).to.equal(expected)
  })
})

Wersja online: https://codepen.io/anon/pen/MrrXam?editors=0010 (normalnie zamiast testów w przeglądarce należy użyć Node'a)

Oczywiście nie skupiam się tu za bardzo na jakości kodu ani samych testów (poprawiłem tylko to co było konieczne).

Ogólniue to polecam najpierw poczytać, bo testy to temat rzeka. No i testy najlepiej pisać przed implementacją.

1 użytkowników online, w tym zalogowanych: 0, gości: 1