Using Jasmine Unit Testing With 100+ Tests Of The Same Type
jasmine, javascript, unit-testing
Solution
You need to create a closure for each of your test, otherwise in your first example you are testing only the last value a lot of time. A clean version of it would look like this :
describe("Numbers Return Correctly", function() {
var tests = { }; // ...
function addTest(test) {
it("Returns Correct String Based On Integer Input " + test, function() {
var number = parseInt(test, 10);
expect(number.convertNumToWord("es")).toEqual(tests[test]);
});
}
for(var test in tests) {
addTest(test);
}
});
Problem
I recently found Jasmine for unit testing, and it seems like a good solution for what I'm doing. However, I'm testing somewhere around 100 different possibilities, and I don't want to write the same line of code over and over. So I made an object full of tests, and I'm looping around the unit test over and over with these tests. It prints out the correct number of tests when I run it. They all pass as shown below. But then I changed "cero" to "cerFOOBARBAZ" and it still passes, which is wrong. Then I change 0 to an arbitrary number (993 for example) and it doesn't pass (and it shouldn't, but ALL tests fail. What's up with that? ``` var tests = { 0 : "cero", 1 : "uno", 2 : "dos", 3 : "tres", 4 : "cuatro", 5 : "cinco", 6 : "seis", 7 : "siete", 8 : "ocho", 9 : "nueve", 10 : "diez", 11 : "once", 12 : "doce", 13 : "trece" }; describe("Numbers Return Correctly", function() { for(var test in tests) { it("Returns Correct String Based On Integer Input", function() { var number = parseInt(test); expect(number.convertNumToWord("es")).toEqual(tests[test]); }); } }); ``` EDIT: I found out what was the problem. I was running the entire describe multiple times, not single specs. However, when I do this: ``` var tests = { 0 : "cero", 1 : "uno", 2 : "dos", 3 : "tres", 4 : "cuatro", 5 : "cinco", 6 : "seis", 7 : "siete", 8 : "ocho", 9 : "nueve", 10 : "diez", 11 : "once", 12 : "doce", 13 : "trece" }; describe("Numbers Return Correctly", function() { //console.log(test); //console.log(tests[test]); it("Returns Correct String Based On Integer Input", function() { for(var test in tests) { var number = parseInt(test); expect(number.convertNumToWord("es")).toEqual(tests[test]); } }); }); ``` I get the expected output, except there are no fine-grained details on which spec didn't pass. Any help there?