'How to cover TypeORM @Column decorator with Jest unit testing?
I want to Unit and e2e test my applications as much as possible and my goal is a coverage of 101%. Problem right now with my setup is, that the @Column decorator from typeorm uses an arrow function to set a default value like the current timestamp on a database update. This arrow function is not covered with jest test coverage. Message is: statement not covered
I run the code coverage with: jest --coverage.
My versions:
"jest": "^24.9.0",
"typeorm": "^0.2.20"
Jest configuration within package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../build/coverage",
"testEnvironment": "node",
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": -10
}
}
},
}
My entity looks like this:
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Role {
@PrimaryGeneratedColumn()
id: number;
@Column()
tenantId: number;
@Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' })
createdAt: Date;
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' })
updatedAt: Date;
}
Coverage for this entity:
(to post an image i need 10 reputation -.-): https://i.ibb.co/FYQgstP/Screenshot-2019-11-07-11-46-45.png
Solution 1:[1]
This is the solution that worked for me, based off of @JayMcDoniel's answer.
- database type:
postgreSQl - testing:
jest/chai
Functions class:
export abstract class EntityDefaultFunctions {
public static defaultNull = (): string => 'NULL';
public static defaultZero = (): string => '0';
}
Tests:
expect(EntityDefaultFunctions.defaultNull()).to.equal('NULL');
expect(EntityDefaultFunctions.defaultZero()).to.equal('0');
Example Entity Column definition:
@Column('text', {
default: EntityDefaultFunctions.defaultNull,
name: 'somePropertyName'
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gmfm |
