I have been working on a project using TypeScript and needed to use TDD to build up some of that project. I wanted to find a way to write my Unit Tests in TypeScript so that I could continue to practice TDD and ensure that my code’s logic was sound. I found tsUnit, a TypeScript Unit Testing Framework. The documentation explains pretty well how to get started with simple unit tests.
After getting a simple test running, I found the need to have a setup function happen before each of my tests run. I couldn’t find any documentation on how to accomplish this from the github documentation or through some quick Google searching. If I want to have something run once before my tests start up I can use the constructor of the TestClass, but I needed this to happen before each test so that they are in a known good state. I found the answer by digging into the tsUnit.ts file itself. To get a function to happen before each test, use the setUp function, this name is the same as the attribute that NUnit uses.
TypeScript itself also provides some value to TDD. I can write a failing test that expects a property or function to exist before it has been defined and the compiler will let me know without needing to run the test that it isn’t going to work. I think thats one of the reasons I have been drawn to TypeScript, it can remove a class of errors at compile time rather than run time.
After getting a simple test running, I found the need to have a setup function happen before each of my tests run. I couldn’t find any documentation on how to accomplish this from the github documentation or through some quick Google searching. If I want to have something run once before my tests start up I can use the constructor of the TestClass, but I needed this to happen before each test so that they are in a known good state. I found the answer by digging into the tsUnit.ts file itself. To get a function to happen before each test, use the setUp function, this name is the same as the attribute that NUnit uses.
constructor() {
super(); //Make sure to call super or TS compiler will complain
console.log(“Once before any test");
}
setUp(){
console.log(“Before each test”);
}
Now I have a few tests defined, I have the data I am using being reset before each one runs and I have the tests’ output on a page so that I can see the results.TypeScript itself also provides some value to TDD. I can write a failing test that expects a property or function to exist before it has been defined and the compiler will let me know without needing to run the test that it isn’t going to work. I think thats one of the reasons I have been drawn to TypeScript, it can remove a class of errors at compile time rather than run time.
Comments
Post a Comment