refactor: move to vitest

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2022-09-12 15:31:48 +08:00
parent dfb1462023
commit 2513f88f44
16 changed files with 899 additions and 1465 deletions

View File

@@ -1,35 +0,0 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const { pathsToModuleNameMapper } = require('ts-jest')
// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
// which contains the path mapping (ie the `compilerOptions.paths` option):
const { compilerOptions } = require('./tsconfig.json')
module.exports = {
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: '.',
testRegex: '.*\\.spec\\.ts$',
collectCoverageFrom: ['**/*.(t|j)s'],
coverageDirectory: '../coverage',
extensionsToTreatAsEsm: ['.ts'],
preset: 'ts-jest',
testEnvironment: 'node',
globals: {
'ts-jest': {
useESM: true,
tsconfig: './test/tsconfig.json',
},
isDev: process.env.NODE_ENV === 'development',
},
setupFiles: ['./test-setup.js'],
moduleNameMapper: {
...pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
'^src/(.*)$': '<rootDir>/src/$1',
'^test/(.*)$': '<rootDir>/test/$1',
'^src$': '<rootDir>/src',
'^~/(.*)$': '<rootDir>/src/$1',
'^~$': '<rootDir>/src',
'^test$': '<rootDir>/test',
},
}

View File

@@ -43,12 +43,7 @@
"prod:pm2": "cross-env NODE_ENV=production pm2 restart ecosystem.config.js",
"prod:stop": "pm2 stop ecosystem.config.js",
"prod:debug": "cross-env NODE_ENV=production nest start --debug --watch",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.js",
"test:all": "jest --config ./test/jest-e2e.js && jest",
"test": "NODE_ENV=development vitest -w",
"docs": "npx @compodoc/compodoc -p tsconfig.json -s -d docs",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
},
@@ -145,6 +140,7 @@
"@nestjs/cli": "9.1.2",
"@nestjs/schematics": "9.0.3",
"@nestjs/testing": "9.0.11",
"@swc/core": "1.3.0",
"@types/babel__core": "7.1.19",
"@types/bcrypt": "5.0.0",
"@types/cache-manager": "4.0.2",
@@ -152,7 +148,6 @@
"@types/ejs": "3.1.1",
"@types/fs-extra": "9.0.13",
"@types/get-image-colors": "4.0.1",
"@types/jest": "29.0.1",
"@types/js-yaml": "4.0.5",
"@types/lodash": "4.14.185",
"@types/marked": "4.0.7",
@@ -171,15 +166,19 @@
"eslint-plugin-unused-imports": "2.0.0",
"husky": "8.0.1",
"ioredis": "5.2.3",
"jest": "29.0.3",
"lint-staged": "13.0.3",
"prettier": "2.7.1",
"rimraf": "3.0.2",
"rollup": "*",
"rollup-plugin-swc": "0.2.1",
"socket.io": "*",
"ts-jest": "28.0.8",
"ts-node": "10.9.1",
"tsconfig-paths": "4.1.0",
"typescript": "4.7.4"
"typescript": "4.7.4",
"vite": "3.1.0",
"vite-tsconfig-paths": "3.5.0",
"vitest": "0.23.2",
"zx": "7.0.8"
},
"optionalDependencies": {
"mongodb-memory-server": "8.9.1",

2167
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,7 @@
import { Controller, ControllerOptions } from '@nestjs/common'
import { API_VERSION } from '~/app.config'
import { isDev } from '~/global/env.global'
export const apiRoutePrefix = isDev ? '' : `/api/v${API_VERSION}`
export const ApiController: (

View File

@@ -1,5 +1,7 @@
import { ApiTags } from '@nestjs/swagger'
import { isDev } from '~/global/env.global'
export const ApiName: ClassDecorator = (target) => {
if (!isDev) {
return

View File

@@ -1,9 +0,0 @@
const { registerGlobals } = require('zx-cjs')
registerGlobals()
const globals = { consola: console, isDev: true, cwd: process.cwd() }
for (const key in globals) {
global[key] = globals[key]
}
process.env.TEST = true

1
test/global.d.ts vendored
View File

@@ -1,6 +1,7 @@
import { Consola } from 'consola'
import { Document, PaginateModel } from 'mongoose'
import 'vitest/globals'
import 'zx-cjs/globals'
import { ModelType } from '@typegoose/typegoose/lib/types'

View File

@@ -1,6 +0,0 @@
module.exports = {
...require('../jest.config'),
rootDir: '..',
testEnvironment: 'node',
testRegex: '.e2e-spec.ts$',
}

1
test/setup-global.ts Normal file
View File

@@ -0,0 +1 @@
export {}

7
test/setup.ts Normal file
View File

@@ -0,0 +1,7 @@
import { register } from '~/global/index.global'
export async function setup() {
await register()
}
export async function teardown() {}

View File

@@ -0,0 +1,16 @@
// @ts-nocheck
import { beforeAll } from 'vitest'
import 'zx/globals'
beforeAll(async () => {
await import('zx/globals')
global.isDev = true
global.cwd = process.cwd()
})
beforeEach(() => {
global.isDev = true
global.cwd = process.cwd()
})

View File

@@ -1,3 +1,5 @@
import { vi } from 'vitest'
import { Test } from '@nestjs/testing'
import { AuthService } from '~/modules/auth/auth.service'
@@ -31,8 +33,8 @@ describe('Test AuthService', () => {
{
provide: getModelToken(UserModel.name),
useValue: {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockResolvedValue({
findById: vi.fn().mockReturnValue({
select: vi.fn().mockResolvedValue({
...mockUser,
}),
}),

View File

@@ -1,5 +1,6 @@
import { dbHelper } from 'test/helper/db-mock.helper'
import { MockCacheService, redisHelper } from 'test/helper/redis-mock.helper'
import { vi } from 'vitest'
import { BadRequestException } from '@nestjs/common'
import { Test } from '@nestjs/testing'
@@ -24,8 +25,9 @@ describe('Test ConfigsService', () => {
await dbHelper.close()
await (await redisHelper).close()
})
const optionModel = getModelForClass(OptionModel)
const mockEmitFn = jest.fn()
const mockEmitFn = vi.fn()
beforeAll(async () => {
const { CacheService: redisService$ } = await redisHelper

View File

@@ -1,3 +1,5 @@
import { vi } from 'vitest'
import { Test } from '@nestjs/testing'
import { CategoryModel } from '~/modules/category/category.model'
@@ -19,33 +21,33 @@ describe('test Markdown Service', () => {
MarkdownService,
{
provide: getModelToken(CategoryModel.name),
useValue: jest.fn(),
useValue: vi.fn(),
},
{
provide: getModelToken(PostModel.name),
useValue: jest.fn(),
useValue: vi.fn(),
},
{
provide: getModelToken(NoteModel.name),
useValue: jest.fn(),
useValue: vi.fn(),
},
{
provide: getModelToken(PageModel.name),
useValue: jest.fn(),
useValue: vi.fn(),
},
{
provide: AssetService,
useValue: jest.fn(),
useValue: vi.fn(),
},
{
provide: DatabaseService,
useValue: jest.fn(),
useValue: vi.fn(),
},
{
provide: TextMacroService,
useValue: {
replaceTextMacro: jest.fn(),
replaceTextMacro: vi.fn(),
},
},
],

View File

@@ -38,7 +38,9 @@ describe('test serverless function service', () => {
{
provide: getModelToken('SnippetModel'),
useValue: getModelForClass(SnippetModel),
useValue: getModelForClass(SnippetModel, {
existingConnection: connection.connection,
}),
},
],
})

70
vitest.config.ts Normal file
View File

@@ -0,0 +1,70 @@
import { resolve } from 'path'
import swc from 'rollup-plugin-swc'
import tsconfigPath from 'vite-tsconfig-paths'
import { defineConfig } from 'vitest/config'
const swcPlugin = (() => {
const plugin = swc({
test: 'ts',
jsc: {
parser: {
syntax: 'typescript',
dynamicImport: true,
decorators: true,
},
target: 'es2021',
transform: {
decoratorMetadata: true,
},
},
})
const originalTransform = plugin.transform!
const transform = function (...args: Parameters<typeof originalTransform>) {
if (!args[1].endsWith('html')) return originalTransform.apply(this, args)
}
return { ...plugin, transform }
})()
export default defineConfig({
root: './test',
test: {
include: ['**/*.spec.ts', '**/*.e2e-spec.ts'],
threads: false,
globals: true,
globalSetup: [resolve(__dirname, './test/setup.ts')],
setupFiles: [resolve(__dirname, './test/setup-global.ts')],
environment: 'node',
includeSource: [resolve(__dirname, './test')],
},
resolve: {
alias: {
'zx-cjs': 'zx',
},
},
// esbuild can not emit ts metadata
esbuild: false,
plugins: [
swcPlugin,
tsconfigPath({
projects: [
resolve(__dirname, './test/tsconfig.json'),
resolve(__dirname, './tsconfig.json'),
],
}),
{
name: 'a-vitest-plugin-that-changes-config',
config: () => ({
test: {
setupFiles: ['./setupFiles/add-something-to-global.ts'],
},
}),
},
],
})