Skip to content

Instantly share code, notes, and snippets.

@Gwash3189
Last active August 29, 2015 13:57
Show Gist options
  • Save Gwash3189/9678351 to your computer and use it in GitHub Desktop.
Save Gwash3189/9678351 to your computer and use it in GitHub Desktop.
Easy mocking with Mock Generic function (Typescipt)
class Person{
private Name: string;
constructor(public Age: number, name: string){
this.Name = name;
}
Older(){
this.Age ++;
}
}
class Student extends Person{
constructor(public Age: number,public StudentNumber: number, name: string){
super(Age,name);
}
Older(){
this.Age ++;
}
Younger(){
this.Age --;
}
}
class PersonSpec implements Mocker.ITestable<PersonSpec,Person>{
Mock = new Mocker.Mock<Person>(Person);
P: Person;
S: Student;
constructor() {
this.P = this.Mock
.With(x => x.Age = 4)
.Private(x => x.Name = "s")
.Create();
//Tests
console.log(P.Age); //4
P.Older();
console.log(P.Age); //5
}
}
module Mocker {
export interface ITestable<SpecClass,Subject>{
Mock: Mocker.Mock<Subject>;
}
export class Mock<T>{
//pass in the 'type'
//'type' is actually a function
private CreatedType: T;
constructor(private Type: any){}
public With(mutator: (obj:T)=>void): Mock<T>{
//avoid compile time error as type is any.
//any can have 0 param constructor
var t = new this.Type();
//set reference to newly created type
this.CreatedType = t;
//pass it into the passed in function
mutator(t);
return this;
}
//lose type safety because of private members
public Private(mutator: (obj: any)=>void): Mock<T>{
if(!this.CreatedType){
var t = new this.Type();
this.CreatedType = t;
}
mutator(t);
return this;
}
public Create(): T{
return this.CreatedType
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment