JadedEric JadedEric - 3 months ago 22
TypeScript Question

Unit testing an exported function in typescript

I'm trying to write a unit test for an export function in typescript, which looks like this:

module mainStream.utilities {
"use strict";

export function getSpriteClassFromDataType(type: string): string {
var retClass: string = "";

if (type) {
switch (type.toString()) {
case "1":
retClass = "text";
break;
case "2":
retClass = "number";
break;
case "3":
retClass = "yesno";
break;
case "4":
retClass = "datetime";
break;
case "9":
retClass = "decimal";
break;
case "10":
retClass = "xml";
break;

default:
retClass = "text";
}
}

return retClass;
}
}


It is a very simple function used to grab the text value from a integer string ("1") = "text"; the code is not the most sufficient way of doing this, as an Enum could most probably have worked, I'm just trying to write a simple test for this.

This is what I have, but Karma complains about the "obj" part and because it's not in a class, I cannot use the namespace (module name) as the object either.

/// <reference path="../../../mainStreamApp/utilities/datatypeclassresolver.ts" />
namespace unit.tests.utilities {
"use strict";

describe("mainStreamApp.utilities", () => {
describe("DataTypeClassResolver", () => {

it("should return the sprite class name for a text data type", () => {
spyOn(mainStreamApp.utilities, "mainStreamApp.utilities.getSpriteClassFromDataType");
let dataType = mainStreamApp.utilities .getSpriteClassFromDataType("1");
expect(mainStreamApp.utilities.getSpriteClassFromDataType).toHaveBeenCalledWith("1");
expect(dataType).toBe("text");
});

});
})
}


Is there a special way to do this, without having to wrap the function in a class?

Answer

spyOn and method call expectation are redundant here. Just call the method and verify result:

it("should return the sprite class name for a text data type", () => {
    let dataType = mainStreamApp.utilities.getSpriteClassFromDataType("1");
    expect(dataType).toBe("text");
});