javascript - Stubbing functions used by other functions within es6 modules -


i've been thinking how test particular functions used other functions within same file.

for example, have 2 functions within 1 file:

// validators.js export const required = ...; export const containsuppercase = ...; export const containsnumber = ...;  export const password = (val) => [required, containsuppercase, containsnumber].every(f => f(val)); 

so clearly, password validator depends on required, containsuppercase , containsnumber functions. if wanted stub out, tests didn't have care functions or how validate.

this simple, silly example, i've ran same problem more complex scenarios.

for example, if try sinon, might try doing this:

import * validators './validators';  sinon.stub(validators, 'required').returns(false); sinon.stub(validators, 'containsuppercase').returns(true); sinon.stub(validators, 'containsnumber').returns(true);  // test expect(validators.password('notimportant')).tobe(false); 

i tried doing this, couldn't work. found work, if did this, though haven't tested it.

const required = ...; const containsuppercase = ...; const containsnumber = ...;  const password = (val) => [ex.required, ex.containsuppercase, ex.containsnumber].every(f => f(val));  export default ex = {   required,   containsuppercase,   containsnumber,   password, } 

this solution ugly, since i'd have worry exporting function in right place, , reference through export object.

is there cleaner way this? or rather, best way test these kinds of functions?

the pattern in second snippet correct. password should refer object methods in order them mocked outside of validators.js scope.

the way achieve behaviour naturally in js using this:

export class validators {   required = (...) => { ... }   ...   password = (val) => [this.required, ...].every(...); }  export default new validators; 

or, normal (non-arrow) functions:

export default {   required(...) {     ...   }   ...   password(val) {     [this.required, ...].every(...);   } } 

in second case required, etc. methods should additionally bound if use this when being called [this.required, ...].every(...).


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -