GitHub - s-take/typescript-express-example
# 依存ライブラリの導入
$ npm i typescript express
# 開発系のライブラリの導入
$ npm i -D ts-node jest supertest ts-jest
# TypeScript用の型の定義の導入
$ npm i @types/express @types/jest @types/supertest
# TypeORM関連(別に必須じゃない)
$ npm install -D typeorm-factory
# CodeBuildで表示するためのレポーター
# https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-jest.html
$ npm install -D jest-junit
"exclude": [
"node_modules",
"__tests__" // テストフォルダを除外
]
module.exports = {
// typescript
"moduleFileExtensions": [
"ts",
"js"
],
"transform": {
"^.+\\.ts$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.json"
}
},
"testMatch": [
// "**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|js)"
],
// coverage
"collectCoverage" : true,
"collectCoverageFrom": ['src/*/*.(ts)'],
"coverageDirectory": "coverage",
// reporter
"reporters": [
'default',
[
'jest-junit',
{
suiteName: 'jest tests',
outputDirectory: 'reports/jest',
outputName: 'js-test-results.xml',
classNameTemplate: '{classname}-{title}',
titleTemplate: '{classname}-{title}',
ancestorSeparator: ' › ',
},
],
],
}
import { User } from './entity/user';
import { getConnection, findByName } from './userRepositorySample';
describe('userRepository', () => {
// あらかじめ、MySQLにデータを入れる
beforeEach(async () => {
const dbConnection = await getConnection();
const user = new User();
user.name = 'testUser';
await dbConnection.manager.save(user);
});
// テストが終わったらMySQLにいれたデータを空にする
afterEach(async () => {
const dbConnection = await getConnection();
await dbConnection.manager.clear(User);
});
it('findByName', async () => {
const user = await findByName('testUser');
expect(user.name).toBe('testUser');
});
});
import app from './apiServer';
import * as request from 'supertest';
describe('APIとして返すテスト', () => {
it('expressサーバー上でAPIの結果を受け取るテスト', async () => {
const response = await request(app).get('/');
expect(response.status).toBe(200);
expect(response.body).toEqual({ hello: 'world' });
});
});