Jest1 is something like one of a hundred different unit testing frameworks for Javascript. I’ve set it up, because the React team is using it.
npm install --save-dev jest-cli
typings install 'dt!jest' --ambient --save
I set this up with TypeScript, but found it required some time fiddling to get it to work.
First, I set up tsconfig.json to put the compiled Javascript files somewhere out of the way, and in CommonJS:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"sourceMap": false,
"outDir": "dist"
},
"exclude": [
"node_modules"
]
}
Your package.json needs a “jest” section added as well – once you set it up, this is what it should look like:
{
"name": "books",
"version": "1.0.0",
"description": "",
"main": "import-editions.ts",
"scripts": {
"test": "jest"
},
"jest": {
"testPathDirs": [
"dist/"
],
"testRegex": "__tests__/.*$"
},
"author": "",
"license": "ISC",
"dependencies": {
},
"devDependencies": {
"jest-cli": "^13.2.3"
}
}
Your code can just go in it’s own file, like you’d normally expect (this is import-editions.ts):
function parseLine(line: string) {
return 'abc'
}
export { parseLine }
Then you can write a test file (put this in __tests__/import-editions-tests.ts):
import { parseLine } from '../import-editions';
jest.unmock('../import-editions');
describe('parseLine', () => {
it('parses the header part of the line', () => {
expect(parseLine('test data')).toBe('abc');
});
});
Once you compile the tests, you can run them without issue.
There are some people out there who use babel as a preprocessor, but I haven’t seen a way to make this work with TypeScript. Some people also use webpack – this is probably the way to go, if you don’t like my approach.
- https://facebook.github.io/jest/ [↩]
Or you could just use https://www.npmjs.com/package/ts-jest 🙂
When I mocked the below class, only the inherited properties are available on the mocked object. The ones defined in the class are not available and when tried to spyOn the methods, an exception is thrown that “x” is not a property.
class B extends A {
public foo() {
}
}
class A {
public bar() {}
}
// SomeOtherTest.js
jest.mock(“./classB”);
const mockedB = new B();
spyOn(mockedB, “foo”); // exception at this line.
I wanted to know why is jest not able to properly mock the objects.