Skip to content

Instantly share code, notes, and snippets.

@trsdln
Last active June 4, 2016 09:38
Show Gist options
  • Save trsdln/6be9c883527ea349c17cab785f1cd2d3 to your computer and use it in GitHub Desktop.
Save trsdln/6be9c883527ea349c17cab785f1cd2d3 to your computer and use it in GitHub Desktop.
TypeScript Unit testing from sractch
//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