Reputation: 362
I am new to Typescript and wanted to implement unit testing with Jest. I installed Jest, and when I run it I receive an error, I have simplified the code for this example, and it continues to fail:
FAIL src\__tests__\validateSender.ts
https validation
ReferenceError: validateSender is not defined
at Object.<anonymous>.test (src/__tests__/validateSender.ts:10:10)
at process._tickCallback (internal/process/next_tick.js:109:7)
The test which cannot find the function (./src/__tests__/validateSender.js
):
import {} from "jest";
const connection = {
encrypted: "undefined",
};
const req = {
connection : ("{connection}"),
};
test("https validation", () => {
expect(validateSender(req)).toThrow();
});
the function (./src/validateSender.js
):
function validateSender(req) {
if (typeof req.connection.encrypted === "undefined") {
throw new CustomException("validateSender", "connection must be secured.");
} else { return; }
}
my Jest package.json portion (./package.json
):
"jest": {
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json"
]
}
I have attempted adding an import statement for the validateSender file directly, but it fails in the same way (on npm test
from the root directory I added import {} from "./src/validateSender";
to the file and received the error above.)
It was also suggested I try import validateSender from "./src/validateSender";
but I receive error TS2307: Cannot find module './src/validateSender'.
It appears that I am missing some foundational knowledge for this process, but I have failed to find it in the TS handbook.
Upvotes: 1
Views: 3696
Reputation: 251222
In order to test a module member, it must be exported. Otherwise it isn't visible to your test.
This doesn't mean you need to export everything - you can test at your public API in most cases and cover the internal members.
Module File
export function validateSender(req) {
if (typeof req.connection.encrypted === "undefined") {
throw new Error("validateSender connection must be secured.");
} else { return; }
}
Test File
import "jest";
import { validateSender } from './ext';
const connection = {
encrypted: "undefined",
};
const req = {
connection: ("{connection}"),
};
test("https validation", () => {
expect(validateSender(req)).toThrow();
});
This will get you this far:
And finally... to expect something to throw, you'll need to adjust your code to:
test("https validation", () => {
expect(() => validateSender(req)).toThrow();
});
This passes an un-executed function that will be executed within the test, rather than executing the function and passing the result.
Upvotes: 1