Last active
June 4, 2016 09:38
-
-
Save trsdln/6be9c883527ea349c17cab785f1cd2d3 to your computer and use it in GitHub Desktop.
TypeScript Unit testing from sractch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//this is test framework | |
class TestCase { | |
protected assertEquals(a,b){ | |
if(a === b){ | |
return true; | |
}else{ | |
throw new Error(`Equals failed: "${a}" is not equal "${b}"`); | |
} | |
} | |
} | |
class TestRunner { | |
private testCases: Array<typeof TestCase>; | |
constructor(){ | |
this.testCases = []; | |
} | |
addTestCase(testCase: typeof TestCase){ | |
this.testCases.push(testCase); | |
} | |
run(){ | |
this.testCases.forEach(testCase => { | |
let testCaseInstance = new testCase(); | |
Object.getOwnPropertyNames(testCase.prototype).forEach(methodName => { | |
if(/^test/.test(methodName)) { | |
try{ | |
testCaseInstance[methodName](); | |
console.log(`Test "${methodName}" [passed]`); | |
}catch(err){ | |
console.error(err.stack); | |
} | |
} | |
}) | |
}); | |
} | |
} | |
//example | |
//testing target | |
class Student { | |
private firstName: String; | |
private lastName: String; | |
constructor(firstName,lastName){ | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
print(){ | |
return `${this.firstName} ${this.lastName}`; | |
} | |
} | |
//my test example | |
class StudentTest extends TestCase{ | |
testConstructor(){ | |
let s = new Student('',''); | |
this.assertEquals(s instanceof Student, true); | |
} | |
testPrint() { | |
let firstName = 'Tom', | |
lastName = 'Doe'; | |
let studentExample = new Student(firstName,lastName); | |
let printResult = studentExample.print(); | |
this.assertEquals(printResult,firstName + ' ' + lastName); | |
} | |
testFoo(){ | |
this.assertEquals(true,true); | |
} | |
testFoo2(){ | |
this.assertEquals(true,true); | |
} | |
testFoo3(){ | |
this.assertEquals(true,true); | |
} | |
} | |
//run tests | |
let testRunner = new TestRunner(); | |
testRunner.addTestCase(StudentTest); | |
testRunner.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment