Skip to content

Commit

Permalink
Merge pull request #18 from sunquakes/development
Browse files Browse the repository at this point in the history
Fixed tests coverage.
  • Loading branch information
sunquakes authored May 31, 2024
2 parents 22d1e89 + 1a0f701 commit 140b412
Show file tree
Hide file tree
Showing 37 changed files with 1,351 additions and 193 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ build/
*.njsproj
*.sln
*.sw?
*.db
*.db

coverage/*
28 changes: 28 additions & 0 deletions __test__/App.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { shallowMount } from '@vue/test-utils'
import App from '../src/App.vue'
import router from '../src/router/index'

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
}))
})

test('Test User.vue', async () => {
const wrapper = shallowMount(App, {
propsData: {},
stubs: ['router-link', 'router-view'],
global: {
plugins: [router]
}
})
expect(wrapper.exists()).toBe(true)
})
56 changes: 56 additions & 0 deletions __test__/api/user.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { pageList, login, del, edit, add } from '../../src/api/user'

jest.mock('../../src/db/sqlite3', () => {
return {
page: jest.fn().mockResolvedValue({
records: [
{
id: 1,
username: 'admin',
password: '123456',
nickname: '管理员'
}
],
total: 1
}),
getOne: jest.fn().mockResolvedValue({
id: 1,
username: 'admin',
password: 'e10adc3949ba59abbe56e057f20f883e',
nickname: '管理员'
}),
remove: jest.fn().mockResolvedValue(1),
updateById: jest.fn().mockResolvedValue(1),
save: jest.fn().mockResolvedValue(1)
}
})

describe('Test user api', () => {
test('Test pageList', async () => {
const res = await pageList(1, 10)
expect(res.total).toBe(1)
})

test('Test login', async () => {
let res = await login('admin', '123456')
expect(res.username).toBe('admin')

res = await login('admin', '1234567')
expect(res).toBeInstanceOf(Error)
})

test('Test del', async () => {
const res = await del([['id', '=', 1]])
expect(res).toBe(1)
})

test('Test edit', async () => {
const res = await edit(1, { nickname: '管理员' })
expect(res).toBe(1)
})

test('Test add', async () => {
const res = await add({ username: 'admin', nickname: '管理员' })
expect(res).toBe(1)
})
})
43 changes: 43 additions & 0 deletions __test__/components/Layout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { mount } from '@vue/test-utils'
import Antd from 'ant-design-vue'
import Layout from '../../src/components/Layout.vue'
import BreadCrumb from '../../src/components/layout/BreadCrumb.vue'
import Footer from '../../src/components/layout/Footer.vue'
import Header from '../../src/components/layout/Header.vue'
import Logo from '../../src/components/layout/Logo.vue'
import Menu from '../../src/components/layout/Menu.vue'
import i18n from '../../src/i18n'
import router from '../../src/router/index'
import store from '../../src/store/index'

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
}))
})

test('Test Layout.vue', async () => {
await router.push({ name: 'User' })
const wrapper = mount(Layout, {
propsData: {},
global: {
plugins: [Antd, router, store, i18n],
components: {
BreadCrumb,
Footer,
Header,
Logo,
Menu
}
}
})
expect(wrapper.exists()).toBe(true)
})
54 changes: 54 additions & 0 deletions __test__/components/Login.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import sqlite3 from 'sqlite3'
import { mount } from '@vue/test-utils'
import Login from '../../src/components/Login.vue'
import Antd from 'ant-design-vue'
import store from '../../src/store'
import i18n from '../../src/i18n'

jest.mock('sqlite3')

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
}))
})

describe('Test Login.vue', () => {
const wrapper = mount(Login, {
propsData: {},
global: {
plugins: [Antd, store, i18n]
}
})

test('Mount component', async () => {
expect(wrapper.exists()).toBe(true)
})

test('Submit the form', async () => {
// Mock database instance
sqlite3.Database = jest.fn().mockImplementation(() => {
return {
get: jest.fn(function (sql, callback) {
callback(undefined, { id: 1, content: 'Hello World!', count: 1 })
})
}
})

// Input username and password.
const usernameInput = wrapper.find('input[id="normal_login_username"]')
const passwordInput = wrapper.find('input[id="normal_login_password"]')
await usernameInput.setValue('admin')
await passwordInput.setValue('admin')

await wrapper.find('form').trigger('submit')
})
})
28 changes: 28 additions & 0 deletions __test__/components/User.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { shallowMount } from '@vue/test-utils'
import User from '../../src/components/User.vue'
import Antd from 'ant-design-vue'
import i18n from '../../src/i18n'

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
}))
})

test('Test User.vue', async () => {
const wrapper = shallowMount(User, {
propsData: {},
global: {
plugins: [Antd, i18n]
}
})
expect(wrapper.exists()).toBe(true)
})
18 changes: 13 additions & 5 deletions __test__/sqlite3.test.js → __test__/db/sqlite3.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sqlite3, { Database } from 'sqlite3'
// @ts-ignore
import sqlite3Rewire, {
options,
execute,
Expand All @@ -9,7 +10,7 @@ import sqlite3Rewire, {
getOne,
updateById,
remove
} from '../src/db/sqlite3'
} from '../../src/db/sqlite3'

jest.mock('sqlite3')

Expand All @@ -22,6 +23,7 @@ test('Test getDb', async () => {
await getDb()
expect(options.db).toBeInstanceOf(Database)

// @ts-ignore
sqlite3.Database = jest.fn().mockImplementation((filePath, callback) => {
if (callback !== undefined) {
callback(new Error('Test'))
Expand All @@ -39,15 +41,19 @@ test('Test Create Table', async () => {
'id Integer PRIMARY KEY AUTOINCREMENT,' +
'content VARCHAR(255) NOT NULL DEFAULT ""' +
')'
sqlite3.Database.prototype.exec = jest.fn((sql, callback) => {
callback()
// @ts-ignore
sqlite3.Database = jest.fn().mockImplementation((filePath, callback) => {
return {
exec: jest.fn((sql, callback) => {})
}
})
options.db = undefined

execute(sql).then((err) => {
expect(err).toBe(undefined)
})

// @ts-ignore
sqlite3.Database = jest.fn().mockImplementation((filePath, callback) => {
return {
exec: jest.fn((sql, callback) => {
Expand Down Expand Up @@ -75,6 +81,7 @@ test('Test options', async () => {

test('Test CRUD', async () => {
// Mock database instance
// @ts-ignore
sqlite3.Database = jest.fn().mockImplementation(() => {
return {
run: jest.fn(function (sql, callback) {
Expand Down Expand Up @@ -102,7 +109,7 @@ test('Test CRUD', async () => {
expect(rows.length).toBeGreaterThan(0)

// Test page.
const pageList = await page('test')
const pageList = await page('test', 1, 10)
expect(pageList.total).toBeGreaterThan(0)

// Test records count.
Expand All @@ -126,6 +133,7 @@ test('Test CRUD', async () => {

test('Test CRUD error', async () => {
// Test error.
// @ts-ignore
sqlite3.Database = jest.fn().mockImplementation(() => {
return {
run: jest.fn(function (sql, callback) {
Expand Down Expand Up @@ -181,7 +189,7 @@ test('Test CRUD error', async () => {
}

try {
await remove('test', ['id', 1])
await remove('test', [['id', 1]])
} catch (e) {
expect(e.message).toBe('Test')
}
Expand Down
1 change: 1 addition & 0 deletions __test__/styleMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {}
7 changes: 7 additions & 0 deletions __test__/utils/date.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { datetime } from '../../src/utils/date'
describe('Test date utils', () => {
test('Test datetime', async () => {
const date = new Date('2024-05-29T00:00:00Z')
expect(datetime(date)).toBe('2024-05-29 00:00:00')
})
})
2 changes: 1 addition & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
plugins: ['babel-plugin-rewire']
}
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
18 changes: 15 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
module.exports = {
transform: {
'\\.js$': 'babel-jest'
'\\.[jt]sx?$': 'babel-jest',
'^[^.]+.vue$': '@vue/vue3-jest'
},
testPathIgnorePatterns: ['<rootDir>/node_modules/'],
collectCoverage: true,
collectCoverageFrom: ['src/db/sqlite3.js'],
collectCoverageFrom: ['src/**/**.vue', 'src/**/**.js', 'src/**/**.ts'],
coverageDirectory: 'coverage',
coverageReporters: ['text', 'lcov']
coverageProvider: 'v8',
coverageReporters: ['text', 'lcov'],
moduleFileExtensions: ['vue', 'js', 'ts'],
testEnvironment: 'jsdom',
testEnvironmentOptions: {
customExportConditions: ['node', 'node-addons']
},
coveragePathIgnorePatterns: ['.d.ts'],
moduleNameMapper: {
'\\.(css|less)$': '<rootDir>/__test__/styleMock.ts'
}
}
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@
"devDependencies": {
"@babel/core": "^7.23.2",
"@babel/preset-env": "^7.23.2",
"@babel/preset-typescript": "^7.24.6",
"@types/crypto-js": "^4.2.2",
"@types/jest": "^29.5.12",
"@vitejs/plugin-vue": "^4.2.3",
"@vue/test-utils": "^2.4.6",
"@vue/vue3-jest": "^29.2.6",
"aws-sdk": "^2.1473.0",
"babel-jest": "^29.7.0",
"babel-plugin-rewire": "^1.2.0",
Expand All @@ -49,6 +54,7 @@
"electron": "^26.3.0",
"electron-builder": "^24.6.4",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"mock-aws-s3": "^4.0.2",
"nock": "^13.3.4",
"sass": "^1.75.0",
Expand Down
4 changes: 3 additions & 1 deletion sonar-project.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
sonar.organization=sunquakes
sonar.projectKey=sunquakes_electron-kits

sonar.exclusions=src/lang/**.js
sonar.tests=__test__
sonar.sources=src
sonar.exclusions=src/lang/**.ts,coverage/**
sonar.javascript.lcov.reportPaths=coverage/lcov.info
14 changes: 14 additions & 0 deletions src/api/user.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export async function pageList(
current: number,
pageSize: number,
where: string[][],
orderBy: string
): Promise<any>

export async function login(username: string, password: string): Promise<any>

export async function del(where: string[][]): Promise<any>

export async function edit(id: number, data: any): Promise<any>

export async function add(data: any): Promise<any>
Loading

0 comments on commit 140b412

Please sign in to comment.