javascript - How to test a function with different inputs -
function addtwo (a, b) { return + b; } //leave function call addtwo(50, 100);
i'm learning react , i'm trying create codecademy type site 'learning project', have run js problem.
say have function above, how test more 1 case? far i'm testing with:
eval(code pulled in here) === 150 ? alert('correct!') : alert('wrong!');
which going alert correct, ok case. other questions (and one) i'm going want more 1 test case , that's i'm stuck.
so, how can test multiple test cases, or there whole other way of doing i'm trying achieve?
any help/tips appreciated,
for know react here's code see bit of have :
const codeeditor = react.createclass({ getinitialstate () { var initialvalue = [ "function addtwo () {", " ", "}", "//leave function call", "addtwo(50, 100);" ].join("\n"); return { katavalue: initialvalue } }, onchange (newvalue) { this.setstate({katavalue: newvalue}); }, evalcode () { var val = this.state.katavalue eval(val) === 150 ? alert('correct!') : alert('wrong!'); }, render () { return ( <div classname="code-editor-wrapper"> <aceeditor name="editor" mode="sh" theme="chaos" onchange={this.onchange} value={this.state.katavalue} editorprops={{$blockscrolling: true}} /> <button onclick={this.evalcode} classname="spec-btn submit-code-btn">evaluate</button> </div> ) } })
don't include function call in user's code. require function named in way. instead of directly evaling user's code, embed function returns user's function:
function getuserfunction(code, functionname) { var usercode = new function(code + '; return ' + functionname + ';'); return usercode(); }
after calling getuserfunction
have reference function user wrote , can execute want. how structure test cases , how feedback want give user you.
here small example:
var userfn = getuserfunction(this.state.katavalue, 'addtwo'); var testcases = [ [[50, 100], 150], [[1, 2], 3], ]; var passes = testcases.every( ([input, output]) => userfn(...input) === output ); if (passes) { // test cases pass }
Comments
Post a Comment