Search code examples
typescriptunit-testingjestjsnestjstypeorm

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:

enter image description here


Solution

  • I ran into a similar issue with GraphQL decorators. As all of these are functions, what you can do is create a file that holds all of the functions you'll be using, name them, and export them, so that you can actually test them as well and get the coverage with Jest. (The tests should literally be something like expect(namedFunction).toBe('CURRENT_TIMESTAMP()') or very similar. For an example you can see my function here and my tests here.

    EDIT 11/03/2020

    The code examples are no more. That being said, you can do things like

    export const returnString = () => String;
    
    @Query(returnString)
    

    for GraphQL. A test for this would look like

    expect(returnString()).toBe(String);