Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do you test your entities? #5567

Closed
artoodeeto opened this issue Feb 25, 2020 · 2 comments
Closed

How do you test your entities? #5567

artoodeeto opened this issue Feb 25, 2020 · 2 comments

Comments

@artoodeeto
Copy link
Contributor

Issue type:

[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[x] mysql / mariadb
[ ] oracle
[ ] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[x] latest
[ ] @next
[ ] 0.x.x (or put your version here)

Steps to reproduce or a small repository showing the problem:

Hello I was wondering how would you go about testing entities?

In ruby on rails you can test for the columns, constraits, and relations. so what Ive been doing is like this.

Post:

import { Entity, PrimaryGeneratedColumn, Column, UpdateDateColumn, ManyToOne, BeforeInsert } from 'typeorm';
import { User } from './user';
import { BaseModel } from './base_model';

@Entity({ name: 'posts' })
export class Post extends BaseModel {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: 'varchar', length: 255 })
  title!: string;

  @Column({ type: 'text', width: 65000 })
  body!: string;

  @Column({ type: 'datetime' })
  createdAt!: Date;

  @UpdateDateColumn()
  updatedAt!: Date;
   
/**
   *  wait for soft delete feature
   */
  // @Column({ type: 'datetime' })
  // deletedAt!: Date;

  @ManyToOne(
    (type) => User,
    (user) => user.posts
  )
  user!: User;

  /**
   * a work around to @CreateDateColumn()
   * TODO: move this to base class
   */
  @BeforeInsert()
  private async setCreatedAtDate() {
    this.createdAt = new Date();
  }
}

Test:

import { Connection, createConnection } from 'typeorm';
import { ValidationError, validate, validateOrReject } from 'class-validator';
import { Post } from '../../src/models/post';
import { testSetup } from '../../config/test_setup';

describe('Post model test', () => {
  let connection: Connection;
  let modelDescription: () => Promise<any>;
  beforeAll(async () => {
    connection = await createConnection(testSetup);
    modelDescription = async () => {
      const columnInformation: Array<any> = await Post.query(`
      DESCRIBE posts
    `);
      return columnInformation.reduce((acc, curr) => {
        acc[curr['Field']] = {
          type: curr['Type'],
          null: curr['Null'],
          default: curr['Default'],
          extra: curr['Extra']
        };
        return acc;
      }, {});
    };
  });

  afterAll(async () => {
    connection.close();
  });

  it('should create a post', async (done) => {
    await Post.create({
      title: 'foo',
      body: 'foo@gmail12as.com'
    }).save();

    const postCount = await Post.findAndCount();

    expect(postCount[1]).toEqual(1);
    done();
  });

  it.only('COLUMN DESCRIPTION', async () => {
    const { id, title, body, createdAt, updatedAt } = await modelDescription();

    expect(id.type).toMatch(/int/);
    expect(id.null).toMatch('NO');
    expect(id.default).toBeNull();

    expect(title.type).toMatch(/varchar/);
    expect(title.null).toMatch('NO');
    expect(title.default).toBeNull();

    expect(body.type).toMatch('mediumtext');
    expect(body.null).toMatch('NO');
    expect(body.default).toBeNull();

    expect(createdAt.type).toMatch('datetime');
    expect(createdAt.null).toMatch('NO');
    expect(createdAt.default).toBeNull();

    expect(updatedAt.type).toMatch('datetime');
    expect(updatedAt.null).toMatch('NO');
    expect(updatedAt.default).toMatch('CURRENT_TIMESTAMP');
    expect(updatedAt.extra).toMatch('DEFAULT_GENERATED');
  });
});

So basically what I've been doing on my test, is describing the column and just do a string comparison on the results. Do you have any other way of testing your entities?. Any suggestions would be appreciated

@ChristianMurphy
Copy link

see #1267

@artoodeeto
Copy link
Contributor Author

@ChristianMurphy thanks for that we have the same idea #1267 (comment) but I wanted to be more simpler. like in rails have_many(:posts) something for validation validate_length_of(:password).to_be(16) but nevermind theres nothing yet. thanks anyway. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants