Skip to content

Commit f074859

Browse files
committed
add test for validate no unnecessary keys
1 parent 3444b9c commit f074859

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

Diff for: __test__/locale.spec.ts

+11-2
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,24 @@ import { describe, it, expect } from 'vitest'
22
import { resolve } from 'node:path'
33
import { readdirSync } from 'node:fs'
44
import { Language } from '../utils/getLanguage'
5-
import { isValid } from './utils'
5+
import { includeAllKeys, excludeKeys } from './utils'
66

77
const locales = readdirSync(resolve(__dirname, '../locales'))
88

99
describe('should include full keys', () => {
1010
const structure: Language = require('../schema/locale.json')
1111
locales.forEach((locale) => {
1212
it(`for ${locale}`, () => {
13-
expect(isValid(require(`../locales/${locale}`), structure)).toBeTruthy()
13+
expect(includeAllKeys(require(`../locales/${locale}`), structure)).toBeTruthy()
14+
})
15+
})
16+
})
17+
18+
describe("shouldn't include unnecessary keys", () => {
19+
const structure: Language = require('../schema/locale.json')
20+
locales.forEach((locale) => {
21+
it(`for ${locale}`, () => {
22+
expect(excludeKeys(require(`../locales/${locale}`), structure)).toBeTruthy()
1423
})
1524
})
1625
})

Diff for: __test__/utils.ts

+22-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* @param schema template for validation
55
* @returns whether missed some keys
66
*/
7-
export function isValid(obj: Object, schema: Object) {
7+
export function includeAllKeys(obj: Object, schema: Object) {
88
for (let key in schema) {
99
if (!obj.hasOwnProperty(key)) {
1010
return false
@@ -15,11 +15,31 @@ export function isValid(obj: Object, schema: Object) {
1515
return false
1616
}
1717
} else if (typeof schema[key] === 'object') {
18-
if (!isValid(obj[key], schema[key])) {
18+
if (!includeAllKeys(obj[key], schema[key])) {
1919
return false
2020
}
2121
}
2222
}
2323
}
2424
return true
2525
}
26+
27+
/**
28+
*
29+
* @param obj object that needs to be validated
30+
* @param schema template for validation
31+
* @returns whether include unnecessary keys
32+
*/
33+
export function excludeKeys(obj: Object, schema: Object) {
34+
for (let key in obj) {
35+
if (!schema.hasOwnProperty(key)) {
36+
return false
37+
}
38+
if (schema[key] !== null && typeof schema[key] === 'object') {
39+
if (!excludeKeys(obj[key], schema[key])) {
40+
return false
41+
}
42+
}
43+
}
44+
return true
45+
}

0 commit comments

Comments
 (0)