diff --git a/.mocharc.yml b/.mocharc.yml index 0eaf156b91..56e4eed74f 100644 --- a/.mocharc.yml +++ b/.mocharc.yml @@ -3,4 +3,3 @@ reporter: spec ui: bdd full-trace: true exit: true -parallel: true diff --git a/lib/extend/generator.ts b/lib/extend/generator.ts index 125d2d3de9..6370f5029e 100644 --- a/lib/extend/generator.ts +++ b/lib/extend/generator.ts @@ -3,20 +3,20 @@ import type { NodeJSLikeCallback } from '../types'; interface BaseObj { path: string; - data: any; - layout?: string; + data?: any; + layout?: string | string[]; } type ReturnType = BaseObj | BaseObj[]; type GeneratorReturnType = ReturnType | Promise; interface GeneratorFunction { - (locals: object, callback?: NodeJSLikeCallback): GeneratorReturnType; + (locals: any, callback?: NodeJSLikeCallback): GeneratorReturnType; } type StoreFunctionReturn = Promise; interface StoreFunction { - (locals: object): StoreFunctionReturn; + (locals: any): StoreFunctionReturn; } interface Store { diff --git a/lib/hexo/index.ts b/lib/hexo/index.ts index 97540dbf5c..b1e32a2762 100644 --- a/lib/hexo/index.ts +++ b/lib/hexo/index.ts @@ -660,7 +660,7 @@ class Hexo extends EventEmitter { }); } - exit(err?: Error): Promise { + exit(err?: any): Promise { if (err) { this.log.fatal( { err }, @@ -674,11 +674,11 @@ class Hexo extends EventEmitter { }); } - execFilter(type: string, data: any, options) { + execFilter(type: string, data: any, options?) { return this.extend.filter.exec(type, data, options); } - execFilterSync(type: string, data: any, options) { + execFilterSync(type: string, data: any, options?) { return this.extend.filter.execSync(type, data, options); } } diff --git a/lib/hexo/multi_config_path.ts b/lib/hexo/multi_config_path.ts index 27c9babd78..6c0ad0b88f 100644 --- a/lib/hexo/multi_config_path.ts +++ b/lib/hexo/multi_config_path.ts @@ -4,7 +4,7 @@ import yml from 'js-yaml'; import { deepMerge } from 'hexo-util'; import type Hexo from './index'; -export = (ctx: Hexo) => function multiConfigPath(base: string, configPaths: string, outputDir: string): string { +export = (ctx: Hexo) => function multiConfigPath(base: string, configPaths?: string, outputDir?: string): string { const { log } = ctx; const defaultPath = join(base, '_config.yml'); diff --git a/lib/hexo/post.ts b/lib/hexo/post.ts index 790a540663..fed51ae5bd 100644 --- a/lib/hexo/post.ts +++ b/lib/hexo/post.ts @@ -231,9 +231,9 @@ interface Result { } interface PostData { - title?: string; + title?: string | number; layout?: string; - slug?: string; + slug?: string | number; path?: string; [prop: string]: any; } @@ -333,7 +333,10 @@ class Post { }); } - publish(data: PostData, replace: boolean, callback?: NodeJSLikeCallback) { + publish(data: PostData, replace?: boolean); + publish(data: PostData, callback?: NodeJSLikeCallback); + publish(data: PostData, replace: boolean, callback?: NodeJSLikeCallback); + publish(data: PostData, replace?: boolean | NodeJSLikeCallback, callback?: NodeJSLikeCallback) { if (!callback && typeof replace === 'function') { callback = replace; replace = false; @@ -366,7 +369,7 @@ class Post { data.content = data._content; data._content = undefined; - return this.create(data, replace); + return this.create(data, replace as boolean); }).then(post => { result.path = post.path; result.content = post.content; diff --git a/lib/hexo/render.ts b/lib/hexo/render.ts index 91ce8e01ff..ce54a18a6b 100644 --- a/lib/hexo/render.ts +++ b/lib/hexo/render.ts @@ -56,7 +56,9 @@ class Render { return this.getRenderer(ext, true); } - render(data: StoreFunctionData, options?: { highlight?: boolean; }, callback?: NodeJSLikeCallback): Promise { + render(data: StoreFunctionData, callback?: NodeJSLikeCallback): Promise; + render(data: StoreFunctionData, options: any, callback?: NodeJSLikeCallback): Promise; + render(data: StoreFunctionData, options?: any | NodeJSLikeCallback, callback?: NodeJSLikeCallback): Promise { if (!callback && typeof options === 'function') { callback = options; options = {}; diff --git a/lib/hexo/router.ts b/lib/hexo/router.ts index 8d9965e483..91d89d51f4 100644 --- a/lib/hexo/router.ts +++ b/lib/hexo/router.ts @@ -84,7 +84,7 @@ class RouteStream extends Readable { } } -const _format = (path: string): string => { +const _format = (path?: string): string => { path = path || ''; if (typeof path !== 'string') throw new TypeError('path must be a string!'); @@ -118,7 +118,7 @@ class Router extends EventEmitter { return Object.keys(routes).filter(key => routes[key]); } - format(path: string): string { + format(path?: string): string { return _format(path); } diff --git a/lib/models/types/moment.ts b/lib/models/types/moment.ts index 121be86248..3de2ab9d25 100644 --- a/lib/models/types/moment.ts +++ b/lib/models/types/moment.ts @@ -16,7 +16,7 @@ class SchemaTypeMoment extends warehouse.SchemaType { super(name, options); } - cast(value, data) { + cast(value?, data?) { value = super.cast(value, data); if (value == null) return value; @@ -29,7 +29,7 @@ class SchemaTypeMoment extends warehouse.SchemaType { return value; } - validate(value, data) { + validate(value, data?) { value = super.validate(value, data); if (value == null) return value; @@ -42,11 +42,11 @@ class SchemaTypeMoment extends warehouse.SchemaType { return value; } - match(value, query, data) { + match(value, query, data?) { return value ? value.valueOf() === query.valueOf() : false; } - compare(a, b) { + compare(a?, b?) { if (a) { if (b) return a - b; return 1; @@ -56,33 +56,33 @@ class SchemaTypeMoment extends warehouse.SchemaType { return 0; } - parse(value) { + parse(value?) { if (value) return toMoment(value); } - value(value, data) { + value(value?, data?) { // FIXME: Same as above. Also a dirty hack. return value ? value._d.toISOString() : value; } - q$day(value, query, data) { + q$day(value, query, data?) { return value ? value.date() === query : false; } - q$month(value, query, data) { + q$month(value, query, data?) { return value ? value.month() === query : false; } - q$year(value, query, data) { + q$year(value, query, data?) { return value ? value.year() === query : false; } - u$inc(value, update, data) { + u$inc(value, update, data?) { if (!value) return value; return value.add(update); } - u$dec(value, update, data) { + u$dec(value, update, data?) { if (!value) return value; return value.subtract(update); } diff --git a/lib/plugins/filter/new_post_path.ts b/lib/plugins/filter/new_post_path.ts index c204303fcf..b25a1f9d2c 100644 --- a/lib/plugins/filter/new_post_path.ts +++ b/lib/plugins/filter/new_post_path.ts @@ -18,7 +18,7 @@ const reservedKeys = { hash: true }; -function newPostPathFilter(this: Hexo, data: PostSchema = {}, replace: boolean): Promise { +function newPostPathFilter(this: Hexo, data: PostSchema = {}, replace?: boolean): Promise { const sourceDir = this.source_dir; const draftDir = join(sourceDir, '_drafts'); const postDir = join(sourceDir, '_posts'); diff --git a/lib/plugins/helper/date.ts b/lib/plugins/helper/date.ts index 4d0451db15..188e8c2a30 100644 --- a/lib/plugins/helper/date.ts +++ b/lib/plugins/helper/date.ts @@ -17,7 +17,7 @@ function getMoment(date: moment.MomentInput | moment.Moment, lang: string, timez return date; } -function toISOString(date: string | number | Date | moment.Moment) { +function toISOString(date?: string | number | Date | moment.Moment) { if (date == null) { return new Date().toISOString(); } @@ -29,19 +29,19 @@ function toISOString(date: string | number | Date | moment.Moment) { return new Date(date as (string | number)).toISOString(); } -function dateHelper(this: LocalsType, date: moment.Moment | moment.MomentInput, format?: string) { +function dateHelper(this: LocalsType, date?: moment.Moment | moment.MomentInput, format?: string) { const { config } = this; const moment = getMoment(date, getLanguage(this), config.timezone); return moment.format(format || config.date_format); } -function timeHelper(this: LocalsType, date: moment.Moment | moment.MomentInput, format?: string) { +function timeHelper(this: LocalsType, date?: moment.Moment | moment.MomentInput, format?: string) { const { config } = this; const moment = getMoment(date, getLanguage(this), config.timezone); return moment.format(format || config.time_format); } -function fullDateHelper(this: LocalsType, date: moment.Moment | moment.MomentInput, format: string) { +function fullDateHelper(this: LocalsType, date?: moment.Moment | moment.MomentInput, format?: string) { if (format) { const moment = getMoment(date, getLanguage(this), this.config.timezone); return moment.format(format); @@ -50,13 +50,13 @@ function fullDateHelper(this: LocalsType, date: moment.Moment | moment.MomentInp return `${this.date(date)} ${this.time(date)}`; } -function relativeDateHelper(this: LocalsType, date: moment.Moment | moment.MomentInput) { +function relativeDateHelper(this: LocalsType, date?: moment.Moment | moment.MomentInput) { const { config } = this; const moment = getMoment(date, getLanguage(this), config.timezone); return moment.fromNow(); } -function timeTagHelper(this: LocalsType, date: string | number | Date | moment.Moment, format: string) { +function timeTagHelper(this: LocalsType, date?: string | number | Date | moment.Moment, format?: string) { return ``; } @@ -72,7 +72,7 @@ function getLanguage(ctx: LocalsType) { * * Moment defined locales: https://github.com/moment/moment/tree/master/locale */ -function _toMomentLocale(lang: string) { +function _toMomentLocale(lang?: string) { if (lang === undefined) { return undefined; } diff --git a/lib/plugins/helper/debug.ts b/lib/plugins/helper/debug.ts index a097223bb9..876756b8f6 100644 --- a/lib/plugins/helper/debug.ts +++ b/lib/plugins/helper/debug.ts @@ -1,7 +1,7 @@ import { inspect } from 'util'; // this format object as string, resolves circular reference -function inspectObject(object: any, options: boolean) { +function inspectObject(object: any, options?: any) { return inspect(object, options); } diff --git a/lib/plugins/helper/feed_tag.ts b/lib/plugins/helper/feed_tag.ts index 818c025ea4..028566bb23 100644 --- a/lib/plugins/helper/feed_tag.ts +++ b/lib/plugins/helper/feed_tag.ts @@ -9,10 +9,10 @@ const feedFn = (str = '') => { interface Options { title?: string; - type?: string; + type?: string | null; } -function makeFeedTag(this: LocalsType, path: string, options: Options = {}, configFeed?: any, configTitle?: string) { +function makeFeedTag(this: LocalsType, path?: string, options: Options = {}, configFeed?: any, configTitle?: string) { const title = options.title || configTitle; if (path) { @@ -47,7 +47,7 @@ function makeFeedTag(this: LocalsType, path: string, options: Options = {}, conf return ''; } -function feedTagHelper(this: LocalsType, path: string, options: Options = {}) { +function feedTagHelper(this: LocalsType, path?: string, options: Options = {}) { const { config } = this; return moize.deep(makeFeedTag.bind(this))(path, options, (config as any).feed, config.title); } diff --git a/lib/plugins/helper/full_url_for.ts b/lib/plugins/helper/full_url_for.ts index 8f4071c2fc..65dd45663d 100644 --- a/lib/plugins/helper/full_url_for.ts +++ b/lib/plugins/helper/full_url_for.ts @@ -2,6 +2,6 @@ import { full_url_for } from 'hexo-util'; import type { LocalsType } from '../../types'; -export = function(this: LocalsType, path: string) { +export = function(this: LocalsType, path?: string) { return full_url_for.call(this, path); } diff --git a/lib/plugins/helper/image_tag.ts b/lib/plugins/helper/image_tag.ts index 6308a883ac..7eec8e2212 100644 --- a/lib/plugins/helper/image_tag.ts +++ b/lib/plugins/helper/image_tag.ts @@ -3,6 +3,7 @@ import type { LocalsType } from '../../types'; interface Options { src?: string; + alt?: string; class?: string | string[]; } diff --git a/lib/plugins/helper/link_to.ts b/lib/plugins/helper/link_to.ts index ce62a61da8..4d7db28a6f 100644 --- a/lib/plugins/helper/link_to.ts +++ b/lib/plugins/helper/link_to.ts @@ -2,6 +2,7 @@ import { htmlTag, url_for } from 'hexo-util'; import type { LocalsType } from '../../types'; interface Options { + id?: string; href?: string; title?: string; external?: boolean | null; @@ -20,7 +21,7 @@ interface Attrs { [key: string]: string | boolean | null | undefined; } -function linkToHelper(this: LocalsType, path: string, text: string, options: Options | boolean = {}) { +function linkToHelper(this: LocalsType, path: string, text?: string, options: Options | boolean = {}) { if (typeof options === 'boolean') options = {external: options}; if (!text) text = path.replace(/^https?:\/\/|\/$/g, ''); diff --git a/lib/plugins/helper/list_archives.ts b/lib/plugins/helper/list_archives.ts index 60824abd33..c4ee26a93a 100644 --- a/lib/plugins/helper/list_archives.ts +++ b/lib/plugins/helper/list_archives.ts @@ -5,7 +5,7 @@ import { url_for } from 'hexo-util'; interface Options { format?: string; type?: string; - style?: string; + style?: string | false; transform?: (name: string) => string; separator?: string; show_count?: boolean; diff --git a/lib/plugins/helper/list_categories.ts b/lib/plugins/helper/list_categories.ts index 26f55e25e2..4fce20a72c 100644 --- a/lib/plugins/helper/list_categories.ts +++ b/lib/plugins/helper/list_categories.ts @@ -3,7 +3,7 @@ import type { CategorySchema, LocalsType } from '../../types'; import type Query from 'warehouse/dist/query'; interface Options { - style?: string; + style?: string | false; class?: string; depth?: number | string; orderby?: string; @@ -13,11 +13,9 @@ interface Options { transform?: (name: string) => string; separator?: string; suffix?: string; - children_indicator?: boolean; + children_indicator?: string | boolean; } -function listCategoriesHelper(this: LocalsType, options?: Options): string; -function listCategoriesHelper(this: LocalsType, categories: Query, options?: Options): string; function listCategoriesHelper(this: LocalsType, categories?: Query | Options, options?: Options) { if (!options && (!categories || !Object.prototype.hasOwnProperty.call(categories, 'length'))) { options = categories as Options; diff --git a/lib/plugins/helper/list_posts.ts b/lib/plugins/helper/list_posts.ts index 10a6223e6b..23353de618 100644 --- a/lib/plugins/helper/list_posts.ts +++ b/lib/plugins/helper/list_posts.ts @@ -3,7 +3,7 @@ import type { LocalsType, PostSchema } from '../../types'; import type Query from 'warehouse/dist/query'; interface Options { - style?: string; + style?: string | false; class?: string; amount?: number; orderby?: string; @@ -12,8 +12,6 @@ interface Options { separator?: string; } -function listPostsHelper(this: LocalsType, options?: Options): string; -function listPostsHelper(this: LocalsType, posts: Query, options?: Options): string; function listPostsHelper(this: LocalsType, posts?: Query | Options, options?: Options) { if (!options && (!posts || !Object.prototype.hasOwnProperty.call(posts, 'length'))) { options = posts as Options; diff --git a/lib/plugins/helper/list_tags.ts b/lib/plugins/helper/list_tags.ts index e09fc0a321..c57e0b8378 100644 --- a/lib/plugins/helper/list_tags.ts +++ b/lib/plugins/helper/list_tags.ts @@ -4,7 +4,7 @@ import type { LocalsType, TagSchema } from '../../types'; import type Query from 'warehouse/dist/query'; interface Options { - style?: string; + style?: string | false; class?: any; amount?: number; orderby?: string; @@ -15,8 +15,6 @@ interface Options { suffix?: string; } -function listTagsHelper(this: LocalsType, options?: Options): string; -function listTagsHelper(this: LocalsType, tags: Query, options?: Options): string; function listTagsHelper(this: LocalsType, tags?: Query | Options, options?: Options) { if (!options && (!tags || !Object.prototype.hasOwnProperty.call(tags, 'length'))) { options = tags as Options; @@ -104,8 +102,7 @@ function listTagsHelper(this: LocalsType, tags?: Query | Options, opt return result; } -function listTagsHelperFactory(options?: Options): string; -function listTagsHelperFactory(tags: Query, options?: Options): string; + function listTagsHelperFactory(tags?: Query | Options, options?: Options) { const transformArgs = () => { if (!options && (!tags || !Object.prototype.hasOwnProperty.call(tags, 'length'))) { diff --git a/lib/plugins/helper/mail_to.ts b/lib/plugins/helper/mail_to.ts index be102ef516..593a3f3733 100644 --- a/lib/plugins/helper/mail_to.ts +++ b/lib/plugins/helper/mail_to.ts @@ -5,16 +5,26 @@ interface Options { href?: string; title?: string; class?: string | string[]; + subject?: string; + cc?: string | string[]; + bcc?: string | string[]; + id?: string; + body?: string; } interface Attrs { href: string; title: string; class?: string; - [key: string]: string | boolean | null | undefined; + subject?: string; + cc?: string; + bcc?: string; + id?: string; + body?: string; + [key: string]: any; } -function mailToHelper(path: string, text: string, options: Options = {}) { +function mailToHelper(path: string | string[], text?: string, options: Options = {}) { if (Array.isArray(path)) path = path.join(','); if (!text) text = path; diff --git a/lib/plugins/helper/markdown.ts b/lib/plugins/helper/markdown.ts index bda3907f50..1ce89b2978 100644 --- a/lib/plugins/helper/markdown.ts +++ b/lib/plugins/helper/markdown.ts @@ -1,6 +1,6 @@ import type { LocalsType } from '../../types'; -function markdownHelper(this: LocalsType, text: string, options: any) { +function markdownHelper(this: LocalsType, text: string, options?: any) { return this.render(text, 'markdown', options); } diff --git a/lib/plugins/helper/number_format.ts b/lib/plugins/helper/number_format.ts index 350e1b1129..477e50e892 100644 --- a/lib/plugins/helper/number_format.ts +++ b/lib/plugins/helper/number_format.ts @@ -1,7 +1,7 @@ interface Options { delimiter?: string; separator?: string; - precision?: number; + precision?: number | false; } function numberFormatHelper(num: number, options: Options = {}) { diff --git a/lib/plugins/helper/partial.ts b/lib/plugins/helper/partial.ts index a0e2eda212..c84d19465a 100644 --- a/lib/plugins/helper/partial.ts +++ b/lib/plugins/helper/partial.ts @@ -7,7 +7,7 @@ interface Options { only?: boolean; } -export = (ctx: Hexo) => function partial(this: LocalsType, name: string, locals: any, options: Options = {}) { +export = (ctx: Hexo) => function partial(this: LocalsType, name: string, locals?: any, options: Options = {}) { if (typeof name !== 'string') throw new TypeError('name must be a string!'); const { cache } = options; diff --git a/lib/plugins/helper/search_form.ts b/lib/plugins/helper/search_form.ts index 4eb414245b..74cd14f33f 100644 --- a/lib/plugins/helper/search_form.ts +++ b/lib/plugins/helper/search_form.ts @@ -3,7 +3,7 @@ import type { LocalsType } from '../../types'; interface Options { class?: string; - text?: string; + text?: string | null; button?: string | boolean; } diff --git a/lib/plugins/helper/tagcloud.ts b/lib/plugins/helper/tagcloud.ts index aeff9a4e87..027d684482 100644 --- a/lib/plugins/helper/tagcloud.ts +++ b/lib/plugins/helper/tagcloud.ts @@ -21,8 +21,6 @@ interface Options { end_color?: string; } -function tagcloudHelper(this: LocalsType, options?: Options); -function tagcloudHelper(this: LocalsType, tags: Query, options?: Options); function tagcloudHelper(this: LocalsType, tags?: Query | Options, options?: Options) { if (!options && (!tags || !Object.prototype.hasOwnProperty.call(tags, 'length'))) { options = tags as Options; @@ -98,8 +96,6 @@ function tagcloudHelper(this: LocalsType, tags?: Query | Options, opt return result.join(separator); } -function tagcloudHelperFactory(this: LocalsType, options?: Options); -function tagcloudHelperFactory(this: LocalsType, tags: Query, options?: Options); function tagcloudHelperFactory(this: LocalsType, tags?: Query | Options, options?: Options) { const transformArgs = () => { if (!options && (!tags || !Object.prototype.hasOwnProperty.call(tags, 'length'))) { diff --git a/lib/plugins/processor/common.ts b/lib/plugins/processor/common.ts index fa5202b633..4b565e7207 100644 --- a/lib/plugins/processor/common.ts +++ b/lib/plugins/processor/common.ts @@ -4,7 +4,7 @@ import micromatch from 'micromatch'; const DURATION_MINUTE = 1000 * 60; -function isMatch(path: string, patterns: string| string[]) { +function isMatch(path: string, patterns?: string| string[]) { if (!patterns) return false; return micromatch.isMatch(path, patterns); @@ -34,7 +34,7 @@ export {isTmpFile}; export {isHiddenFile}; export {isExcludedFile}; -export function toDate(date: string | number | Date) { +export function toDate(date?: string | number | Date | moment.Moment) { if (!date || moment.isMoment(date)) return date; if (!(date instanceof Date)) { @@ -46,7 +46,7 @@ export function toDate(date: string | number | Date) { return date; } -export function timezone(date: Date, timezone: string) { +export function timezone(date: Date | moment.Moment, timezone: string) { if (moment.isMoment(date)) date = date.toDate(); const offset = date.getTimezoneOffset(); diff --git a/lib/plugins/processor/post.ts b/lib/plugins/processor/post.ts index c9ec3a1a86..ea8762944a 100644 --- a/lib/plugins/processor/post.ts +++ b/lib/plugins/processor/post.ts @@ -55,7 +55,7 @@ export = (ctx: Hexo) => { return result; }), - process: function postProcessor(file) { + process: function postProcessor(file: _File) { if (file.params.renderable) { return processPost(ctx, file); } else if (ctx.config.post_asset_folder) { diff --git a/lib/plugins/renderer/nunjucks.ts b/lib/plugins/renderer/nunjucks.ts index 1b854f1ebc..b8a82bea43 100644 --- a/lib/plugins/renderer/nunjucks.ts +++ b/lib/plugins/renderer/nunjucks.ts @@ -56,7 +56,7 @@ function njkCompile(data: StoreFunctionData): nunjucks.Template { return nunjucks.compile(text as string, env, data.path); } -function njkRenderer(data: StoreFunctionData, locals: object): string { +function njkRenderer(data: StoreFunctionData, locals?: any): string { return njkCompile(data).render(locals); } diff --git a/lib/plugins/tag/post_link.ts b/lib/plugins/tag/post_link.ts index 67289df469..9aec591a9d 100644 --- a/lib/plugins/tag/post_link.ts +++ b/lib/plugins/tag/post_link.ts @@ -41,7 +41,13 @@ export = (ctx: Hexo) => { const attrTitle = escapeHTML(post.title || post.slug); if (escape === 'true') title = escapeHTML(title); - const url = new URL(post.path, ctx.config.url).pathname + (hash ? `#${hash}` : ''); + // guarantee the base url ends with a slash. (case of using a subdirectory in the url of the site) + let baseUrl = ctx.config.url; + if (!baseUrl.endsWith('/')) { + baseUrl += '/'; + } + + const url = new URL(post.path, baseUrl).pathname + (hash ? `#${hash}` : ''); const link = encodeURL(url); return `${title}`; diff --git a/lib/theme/view.ts b/lib/theme/view.ts index c693a3ded5..7c7887a3f3 100644 --- a/lib/theme/view.ts +++ b/lib/theme/view.ts @@ -22,6 +22,7 @@ const assignIn = (target: any, ...sources: any[]) => { class Options { layout?: any; + [key: string]: any; } class View { diff --git a/lib/types.ts b/lib/types.ts index a22c081182..4ca98f4e16 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -82,7 +82,7 @@ export interface PostSchema { current?: number; total?: number; description?: string; - + [key: string]: any; } export interface PageSchema { diff --git a/package.json b/package.json index 0150fb28b1..b6bec8d9b1 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "clean": "tsc -b --clean", "eslint": "eslint lib test", "pretest": "npm run clean && npm run build", - "test": "mocha test/index.js --require ts-node/register", + "test": "mocha test/scripts/**/*.ts --require ts-node/register", "test-cov": "c8 --reporter=lcovonly npm test -- --no-parallel", "prepare": "husky install" }, @@ -66,13 +66,16 @@ "warehouse": "^5.0.1" }, "devDependencies": { + "0x": "^5.1.2", "@types/abbrev": "^1.1.3", "@types/bluebird": "^3.5.37", + "@types/chai": "^4.3.11", "@types/js-yaml": "^4.0.9", + "@types/mocha": "^10.0.6", "@types/node": "^18.11.8 <18.19.9", "@types/nunjucks": "^3.2.2", + "@types/sinon": "^17.0.3", "@types/text-table": "^0.2.4", - "0x": "^5.1.2", "c8": "^9.0.0", "chai": "^4.3.6", "cheerio": "0.22.0", diff --git a/test/fixtures/.eslintrc b/test/fixtures/.eslintrc new file mode 100644 index 0000000000..f25990b7d4 --- /dev/null +++ b/test/fixtures/.eslintrc @@ -0,0 +1,6 @@ +{ + "extends": "hexo/ts", + "rules": { + "node/no-unsupported-features/es-syntax": 0 + } +} \ No newline at end of file diff --git a/test/fixtures/post_render.js b/test/fixtures/post_render.ts similarity index 88% rename from test/fixtures/post_render.js rename to test/fixtures/post_render.ts index f9e7351b49..c631822a29 100644 --- a/test/fixtures/post_render.js +++ b/test/fixtures/post_render.ts @@ -1,13 +1,11 @@ -'use strict'; - -const { highlight } = require('hexo-util'); +import { highlight } from 'hexo-util'; const code = [ 'if tired && night:', ' sleep()' ].join('\n'); -exports.content = [ +export const content = [ '# Title', '``` python', code, @@ -24,7 +22,7 @@ exports.content = [ '{% endquote %}' ].join('\n'); -exports.expected = [ +export const expected = [ '

Title

', highlight(code, {lang: 'python'}), '\n

some content

\n', @@ -36,7 +34,7 @@ exports.expected = [ '
Hello World
' ].join(''); -exports.expected_disable_nunjucks = [ +export const expected_disable_nunjucks = [ '

Title

', highlight(code, {lang: 'python'}), '\n

some content

\n', @@ -49,7 +47,7 @@ exports.expected_disable_nunjucks = [ '{% endquote %}

' ].join(''); -exports.content_for_issue_3346 = [ +export const content_for_issue_3346 = [ '# Title', '```', '{% test1 %}', @@ -63,7 +61,7 @@ exports.content_for_issue_3346 = [ '{% endblockquote %}' ].join('\n'); -exports.expected_for_issue_3346 = [ +export const expected_for_issue_3346 = [ '

Title

', highlight('{% test1 %}\n{{ test2 }}').replace(/{/g, '{').replace(/}/g, '}'), // Escaped by backtick_code_block '\n

some content

\n', @@ -73,7 +71,7 @@ exports.expected_for_issue_3346 = [ '' ].join(''); -exports.content_for_issue_4460 = [ +export const content_for_issue_4460 = [ '```html', '', '', diff --git a/test/index.js b/test/index.js deleted file mode 100644 index 5baf989398..0000000000 --- a/test/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const chai = require('chai'); -global.should = chai.should(); - -describe('Hexo', () => { - require('./scripts/box'); - require('./scripts/console'); - require('./scripts/extend'); - require('./scripts/filters'); - require('./scripts/generators'); - require('./scripts/helpers'); - require('./scripts/hexo'); - require('./scripts/models'); - require('./scripts/processors'); - require('./scripts/renderers'); - require('./scripts/tags'); - require('./scripts/theme'); - require('./scripts/theme_processors'); -}); diff --git a/test/scripts/.eslintrc b/test/scripts/.eslintrc new file mode 100644 index 0000000000..07fa788f2a --- /dev/null +++ b/test/scripts/.eslintrc @@ -0,0 +1,13 @@ +{ + "extends": "hexo/ts-test", + "rules": { + "@typescript-eslint/no-explicit-any": 0, + "@typescript-eslint/ban-ts-comment": 0, + "@typescript-eslint/no-non-null-assertion": 0, + "node/no-unsupported-features/es-syntax": 0, + "@typescript-eslint/no-var-requires": 0, + "@typescript-eslint/no-empty-function": 0, + "@typescript-eslint/no-unused-vars": 0, + "node/no-missing-require": 0 + } +} \ No newline at end of file diff --git a/test/scripts/box/box.js b/test/scripts/box/box.ts similarity index 96% rename from test/scripts/box/box.js rename to test/scripts/box/box.ts index 4aaebd8698..d6d3d35b57 100644 --- a/test/scripts/box/box.js +++ b/test/scripts/box/box.ts @@ -1,17 +1,18 @@ -'use strict'; - -const { join, sep } = require('path'); -const { appendFile, mkdir, mkdirs, rename, rmdir, stat, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); -const { hash, Pattern } = require('hexo-util'); -const { spy, match, assert: sinonAssert } = require('sinon'); +import { join, sep } from 'path'; +import { appendFile, mkdir, mkdirs, rename, rmdir, stat, unlink, writeFile } from 'hexo-fs'; +import { hash, Pattern } from 'hexo-util'; +import { spy, match, assert as sinonAssert } from 'sinon'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import Box from '../../../lib/box'; +import chai from 'chai'; +const should = chai.should(); describe('Box', () => { - const Hexo = require('../../../dist/hexo'); const baseDir = join(__dirname, 'box_tmp'); - const Box = require('../../../dist/box').default; - const newBox = (path, config) => { + const newBox = (path?, config?) => { const hexo = new Hexo(baseDir, { silent: true }); hexo.config = Object.assign(hexo.config, config); const base = path ? join(baseDir, path) : baseDir; @@ -64,13 +65,13 @@ describe('Box', () => { it('addProcessor() - no fn', () => { const box = newBox(); - + // @ts-ignore should.throw(() => box.addProcessor('test'), 'fn must be a function'); }); it('process()', async () => { const box = newBox('test'); - const data = {}; + const data: Record = {}; box.addProcessor(file => { data[file.path] = file; @@ -274,7 +275,7 @@ describe('Box', () => { it('process() - skip files if they match a glob epression in ignore', async () => { const box = newBox('test', { ignore: '**/ignore_me' }); - const data = {}; + const data: object = {}; box.addProcessor(file => { data[file.path] = file; @@ -584,7 +585,7 @@ describe('Box', () => { it('watch() - run process() before start watching', async () => { const box = newBox('test'); - const data = []; + const data: string[] = []; box.addProcessor(file => { data.push(file.path); diff --git a/test/scripts/box/file.js b/test/scripts/box/file.ts similarity index 85% rename from test/scripts/box/file.js rename to test/scripts/box/file.ts index f2fe533b4c..edb485d812 100644 --- a/test/scripts/box/file.js +++ b/test/scripts/box/file.ts @@ -1,13 +1,11 @@ -'use strict'; - -const { join } = require('path'); -const { rmdir, stat, statSync, writeFile } = require('hexo-fs'); -const { load } = require('js-yaml'); +import { join } from 'path'; +import { rmdir, stat, statSync, writeFile } from 'hexo-fs'; +import { load } from 'js-yaml'; +import Hexo from '../../../lib/hexo'; +import Box from '../../../lib/box'; describe('File', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const Box = require('../../../dist/box').default; const box = new Box(hexo, join(hexo.base_dir, 'file_test')); const { File } = box; diff --git a/test/scripts/box/index.js b/test/scripts/box/index.js deleted file mode 100644 index c2a69e5459..0000000000 --- a/test/scripts/box/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -describe('Box', () => { - require('./box'); - require('./file'); -}); diff --git a/test/scripts/console/clean.js b/test/scripts/console/clean.ts similarity index 69% rename from test/scripts/console/clean.js rename to test/scripts/console/clean.ts index f0efb0dcac..509bf2a7bb 100644 --- a/test/scripts/console/clean.js +++ b/test/scripts/console/clean.ts @@ -1,16 +1,18 @@ -'use strict'; - -const { exists, mkdirs, unlink, writeFile } = require('hexo-fs'); +import { exists, mkdirs, unlink, writeFile } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import cleanConsole from '../../../lib/plugins/console/clean'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('clean', () => { - const Hexo = require('../../../dist/hexo'); - let hexo, clean; + let hexo: Hexo, clean: (...args: OriginalParams) => OriginalReturn; beforeEach(() => { hexo = new Hexo(__dirname, {silent: true}); - clean = require('../../../dist/plugins/console/clean').bind(hexo); + clean = cleanConsole.bind(hexo); }); + it('delete database', async () => { const dbPath = hexo.database.options.path; diff --git a/test/scripts/console/config.js b/test/scripts/console/config.ts similarity index 76% rename from test/scripts/console/config.js rename to test/scripts/console/config.ts index 9ed935e19b..3395e12756 100644 --- a/test/scripts/console/config.js +++ b/test/scripts/console/config.ts @@ -1,14 +1,17 @@ -'use strict'; - -const { mkdirs, readFile, rmdir, unlink, writeFile } = require('hexo-fs'); -const { join } = require('path'); -const { load } = require('js-yaml'); -const { stub, assert: sinonAssert } = require('sinon'); +import { mkdirs, readFile, rmdir, unlink, writeFile } from 'hexo-fs'; +import { join } from 'path'; +import { load } from 'js-yaml'; +import { stub, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import configConsole from '../../../lib/plugins/console/config'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; +import chai from 'chai'; +const should = chai.should(); describe('config', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'config_test'), {silent: true}); - const config = require('../../../dist/plugins/console/config').bind(hexo); + const config: (...args: OriginalParams) => OriginalReturn = configConsole.bind(hexo); before(async () => { await mkdirs(hexo.base_dir); @@ -47,13 +50,14 @@ describe('config', () => { const logStub = stub(console, 'log'); try { - hexo.config.server = { + (hexo.config as any).server = { port: 12345 }; await config({_: ['server.port']}); - sinonAssert.calledWith(logStub, hexo.config.server.port); + sinonAssert.calledWith(logStub, (hexo.config as any).server.port); } finally { + // @ts-ignore delete hexo.config.server; logStub.restore(); } @@ -61,8 +65,8 @@ describe('config', () => { async function writeConfig(...args) { await config({_: args}); - const content = await readFile(hexo.config_path); - return load(content); + const content = await readFile(hexo.config_path) as string; + return load(content) as any; } it('write config', async () => { @@ -103,7 +107,7 @@ describe('config', () => { await config({_: ['title', 'My Blog']}); return readFile(configPath).then(content => { - const json = JSON.parse(content); + const json = JSON.parse(content as string); json.title.should.eql('My Blog'); diff --git a/test/scripts/console/deploy.js b/test/scripts/console/deploy.ts similarity index 82% rename from test/scripts/console/deploy.js rename to test/scripts/console/deploy.ts index 86e0c16675..efcb98f5d4 100644 --- a/test/scripts/console/deploy.js +++ b/test/scripts/console/deploy.ts @@ -1,13 +1,16 @@ -'use strict'; - -const { exists, mkdirs, readFile, rmdir, writeFile } = require('hexo-fs'); -const { join } = require('path'); -const { spy, stub, assert: sinonAssert } = require('sinon'); +import { exists, mkdirs, readFile, rmdir, writeFile } from 'hexo-fs'; +import { join } from 'path'; +import { spy, stub, assert as sinonAssert } from 'sinon'; +import chai from 'chai'; +const should = chai.should(); +import Hexo from '../../../lib/hexo'; +import deployConsole from '../../../lib/plugins/console/deploy'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('deploy', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'deploy_test'), { silent: true }); - const deploy = require('../../../dist/plugins/console/deploy').bind(hexo); + const deploy: (...args: OriginalParams) => OriginalReturn = deployConsole.bind(hexo); before(async () => { await mkdirs(hexo.public_dir); @@ -22,6 +25,7 @@ describe('deploy', () => { after(() => rmdir(hexo.base_dir)); it('no deploy config', () => { + // @ts-ignore delete hexo.config.deploy; const logStub = stub(console, 'log'); @@ -97,7 +101,7 @@ describe('deploy', () => { const hexo = new Hexo(join(__dirname, 'deploy_test')); hexo.log.error = logSpy; - const deploy = require('../../../dist/plugins/console/deploy').bind(hexo); + const deploy: (...args: OriginalParams) => OriginalReturn = deployConsole.bind(hexo); hexo.extend.deployer.register('baz', () => { }); hexo.config.deploy = { diff --git a/test/scripts/console/generate.js b/test/scripts/console/generate.ts similarity index 92% rename from test/scripts/console/generate.js rename to test/scripts/console/generate.ts index d4b39ef337..bf6a04615e 100644 --- a/test/scripts/console/generate.js +++ b/test/scripts/console/generate.ts @@ -1,14 +1,17 @@ -'use strict'; - -const { join } = require('path'); -const { emptyDir, exists, mkdirs, readFile, rmdir, stat, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); -const { spy } = require('sinon'); +import { join } from 'path'; +import { emptyDir, exists, mkdirs, readFile, rmdir, stat, unlink, writeFile } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import { spy } from 'sinon'; +import chai from 'chai'; +const should = chai.should(); +import Hexo from '../../../lib/hexo'; +import generateConsole from '../../../lib/plugins/console/generate'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('generate', () => { - const Hexo = require('../../../dist/hexo'); - const generateConsole = require('../../../dist/plugins/console/generate'); - let hexo, generate; + let hexo: Hexo, generate: (...args: OriginalParams) => OriginalReturn; beforeEach(async () => { hexo = new Hexo(join(__dirname, 'generate_test'), {silent: true}); @@ -26,7 +29,7 @@ describe('generate', () => { } }); - const testGenerate = async options => { + const testGenerate = async (options?: any) => { await Promise.all([ // Add some source files writeFile(join(hexo.source_dir, 'test.txt'), 'test'), @@ -300,17 +303,15 @@ describe('generate', () => { }); it('should generate all files even when concurrency is set', async () => { - await generate({ concurrency: 1 }); - return generate({ concurrency: 2 }); + await generate({ concurrency: '1' }); + return generate({ concurrency: '2' }); }); }); // #3975 workaround for Windows describe('generate - watch (delete)', () => { - const Hexo = require('../../../dist/hexo'); - const generateConsole = require('../../../dist/plugins/console/generate'); const hexo = new Hexo(join(__dirname, 'generate_test'), {silent: true}); - const generate = generateConsole.bind(hexo); + const generate: (...args: OriginalParams) => OriginalReturn = generateConsole.bind(hexo); beforeEach(async () => { await mkdirs(hexo.base_dir); diff --git a/test/scripts/console/index.js b/test/scripts/console/index.js deleted file mode 100644 index 94ef2ffd02..0000000000 --- a/test/scripts/console/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -describe('Console', () => { - require('./clean'); - require('./config'); - require('./deploy'); - require('./generate'); - require('./migrate'); - require('./new'); - require('./publish'); - require('./render'); - require('./list'); - require('./list_post'); - require('./list_categories'); - require('./list_tags'); - require('./list_page'); - require('./list_route'); -}); diff --git a/test/scripts/console/list.js b/test/scripts/console/list.js deleted file mode 100644 index 124274888d..0000000000 --- a/test/scripts/console/list.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -const { spy, stub, assert: sinonAssert } = require('sinon'); -const Promise = require('bluebird'); - -describe('Console list', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(__dirname); - - it('no args', () => { - hexo.call = spy(); - - const list = require('../../../dist/plugins/console/list').bind(hexo); - - list({ _: [''] }); - - hexo.call.calledOnce.should.be.true; - hexo.call.args[0][0].should.eql('help'); - hexo.call.args[0][1]._[0].should.eql('list'); - }); - - it('has args', async () => { - const logStub = stub(console, 'log'); - - hexo.load = () => Promise.resolve(); - - const list = require('../../../dist/plugins/console/list').bind(hexo); - - await list({ _: ['page'] }); - - sinonAssert.calledWithMatch(logStub, 'Date'); - sinonAssert.calledWithMatch(logStub, 'Title'); - sinonAssert.calledWithMatch(logStub, 'Path'); - sinonAssert.calledWithMatch(logStub, 'No pages.'); - logStub.restore(); - }); - - it('list type not found', () => { - hexo.call = spy(); - - const list = require('../../../dist/plugins/console/list').bind(hexo); - - list({ _: ['test'] }); - - hexo.call.calledOnce.should.be.true; - hexo.call.args[0][0].should.eql('help'); - hexo.call.args[0][1]._[0].should.eql('list'); - }); -}); diff --git a/test/scripts/console/list.ts b/test/scripts/console/list.ts new file mode 100644 index 0000000000..0aa0b8ec24 --- /dev/null +++ b/test/scripts/console/list.ts @@ -0,0 +1,51 @@ +import { spy, stub, assert as sinonAssert, SinonSpy } from 'sinon'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import listConsole from '../../../lib/plugins/console/list'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; + +describe('Console list', () => { + const hexo = new Hexo(__dirname); + + it('no args', () => { + hexo.call = spy(); + + const list: (...args: OriginalParams) => OriginalReturn = listConsole.bind(hexo); + + list({ _: [''] }); + + (hexo.call as SinonSpy).calledOnce.should.be.true; + (hexo.call as SinonSpy).args[0][0].should.eql('help'); + (hexo.call as SinonSpy).args[0][1]._[0].should.eql('list'); + }); + + it('has args', async () => { + const logStub = stub(console, 'log'); + + hexo.load = () => Promise.resolve(); + + const list: (...args: OriginalParams) => OriginalReturn = listConsole.bind(hexo); + + await list({ _: ['page'] }); + + sinonAssert.calledWithMatch(logStub, 'Date'); + sinonAssert.calledWithMatch(logStub, 'Title'); + sinonAssert.calledWithMatch(logStub, 'Path'); + sinonAssert.calledWithMatch(logStub, 'No pages.'); + logStub.restore(); + }); + + it('list type not found', () => { + hexo.call = spy(); + + const list: (...args: OriginalParams) => OriginalReturn = listConsole.bind(hexo); + + list({ _: ['test'] }); + + (hexo.call as SinonSpy).calledOnce.should.be.true; + (hexo.call as SinonSpy).args[0][0].should.eql('help'); + (hexo.call as SinonSpy).args[0][1]._[0].should.eql('list'); + }); +}); diff --git a/test/scripts/console/list_categories.js b/test/scripts/console/list_categories.ts similarity index 74% rename from test/scripts/console/list_categories.js rename to test/scripts/console/list_categories.ts index 5a67aa93be..2a5d47fb76 100644 --- a/test/scripts/console/list_categories.js +++ b/test/scripts/console/list_categories.ts @@ -1,14 +1,16 @@ -'use strict'; - -const Promise = require('bluebird'); -const { stub, assert: sinonAssert } = require('sinon'); +// @ts-ignore +import Promise from 'bluebird'; +import { stub, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import listCategory from '../../../lib/plugins/console/list/category'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('Console list', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); - const listCategories = require('../../../dist/plugins/console/list/category').bind(hexo); + const listCategories: (...args: OriginalParams) => OriginalReturn = listCategory.bind(hexo); let logStub; diff --git a/test/scripts/console/list_page.js b/test/scripts/console/list_page.ts similarity index 79% rename from test/scripts/console/list_page.js rename to test/scripts/console/list_page.ts index dc8fd444ba..2c77ab7f82 100644 --- a/test/scripts/console/list_page.js +++ b/test/scripts/console/list_page.ts @@ -1,12 +1,13 @@ -'use strict'; - -const { stub, assert: sinonAssert } = require('sinon'); +import { stub, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import listPage from '../../../lib/plugins/console/list/page'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('Console list', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Page = hexo.model('Page'); - const listPages = require('../../../dist/plugins/console/list/page').bind(hexo); + const listPages: (...args: OriginalParams) => OriginalReturn = listPage.bind(hexo); hexo.config.permalink = ':title/'; diff --git a/test/scripts/console/list_post.js b/test/scripts/console/list_post.ts similarity index 81% rename from test/scripts/console/list_post.js rename to test/scripts/console/list_post.ts index 64ab652d3b..72f92a44b1 100644 --- a/test/scripts/console/list_post.js +++ b/test/scripts/console/list_post.ts @@ -1,14 +1,16 @@ -'use strict'; - -const Promise = require('bluebird'); -const { stub, assert: sinonAssert } = require('sinon'); +// @ts-ignore +import Promise from 'bluebird'; +import { stub, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import listPost from '../../../lib/plugins/console/list/post'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('Console list', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); - const listPosts = require('../../../dist/plugins/console/list/post').bind(hexo); + const listPosts: (...args: OriginalParams) => OriginalReturn = listPost.bind(hexo); let logStub; diff --git a/test/scripts/console/list_route.js b/test/scripts/console/list_route.ts similarity index 69% rename from test/scripts/console/list_route.js rename to test/scripts/console/list_route.ts index 3169544ad4..295378c79e 100644 --- a/test/scripts/console/list_route.js +++ b/test/scripts/console/list_route.ts @@ -1,12 +1,13 @@ -'use strict'; - -const { stub, assert: sinonAssert } = require('sinon'); +import { stub, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import listRoute from '../../../lib/plugins/console/list/route'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('Console list', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const listRoutes = require('../../../dist/plugins/console/list/route').bind(hexo); + const listRoutes: (...args: OriginalParams) => OriginalReturn = listRoute.bind(hexo); const { route } = hexo; let logStub; diff --git a/test/scripts/console/list_tags.js b/test/scripts/console/list_tags.ts similarity index 78% rename from test/scripts/console/list_tags.js rename to test/scripts/console/list_tags.ts index 01073f7b14..4be2747913 100644 --- a/test/scripts/console/list_tags.js +++ b/test/scripts/console/list_tags.ts @@ -1,14 +1,16 @@ -'use strict'; - -const Promise = require('bluebird'); -const { stub, assert: sinonAssert } = require('sinon'); +// @ts-ignore +import Promise from 'bluebird'; +import { stub, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import listTag from '../../../lib/plugins/console/list/tag'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('Console list', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); - const listTags = require('../../../dist/plugins/console/list/tag').bind(hexo); + const listTags: (...args: OriginalParams) => OriginalReturn = listTag.bind(hexo); hexo.config.permalink = ':title/'; diff --git a/test/scripts/console/migrate.js b/test/scripts/console/migrate.ts similarity index 56% rename from test/scripts/console/migrate.js rename to test/scripts/console/migrate.ts index a277197d4e..f40de2e1ae 100644 --- a/test/scripts/console/migrate.js +++ b/test/scripts/console/migrate.ts @@ -1,11 +1,12 @@ -'use strict'; - -const { spy, assert: sinonAssert, stub } = require('sinon'); +import { spy, assert as sinonAssert, stub, SinonSpy } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import migrateConsole from '../../../lib/plugins/console/migrate'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('migrate', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname, { silent: true }); - const migrate = require('../../../dist/plugins/console/migrate').bind(hexo); + const migrate: (...args: OriginalParams) => OriginalReturn = migrateConsole.bind(hexo); it('default', async () => { const migrator = spy(); @@ -21,12 +22,12 @@ describe('migrate', () => { it('no args', async () => { const hexo = new Hexo(__dirname, { silent: true }); hexo.call = spy(); - const migrate = require('../../../dist/plugins/console/migrate').bind(hexo); + const migrate: (...args: OriginalParams) => OriginalReturn = migrateConsole.bind(hexo); await migrate({ _: [] }); - hexo.call.calledOnce.should.be.true; - hexo.call.args[0][0].should.eql('help'); - hexo.call.args[0][1]._[0].should.eql('migrate'); + (hexo.call as SinonSpy).calledOnce.should.be.true; + (hexo.call as SinonSpy).args[0][0].should.eql('help'); + (hexo.call as SinonSpy).args[0][1]._[0].should.eql('migrate'); }); it('migrator not found', async () => { diff --git a/test/scripts/console/new.js b/test/scripts/console/new.ts similarity index 92% rename from test/scripts/console/new.js rename to test/scripts/console/new.ts index 4fd68eaf62..9ff8fb4bb4 100644 --- a/test/scripts/console/new.js +++ b/test/scripts/console/new.ts @@ -1,16 +1,17 @@ -'use strict'; - -const { exists, mkdirs, readFile, rmdir, unlink } = require('hexo-fs'); -const moment = require('moment'); -const { join } = require('path'); -const Promise = require('bluebird'); -const { useFakeTimers } = require('sinon'); -const { spy } = require('sinon'); +import { exists, mkdirs, readFile, rmdir, unlink } from 'hexo-fs'; +import moment from 'moment'; +import { join } from 'path'; +// @ts-ignore +import Promise from 'bluebird'; +import { useFakeTimers, spy, SinonSpy } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import newConsole from '../../../lib/plugins/console/new'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('new', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'new_test'), {silent: true}); - const n = require('../../../dist/plugins/console/new').bind(hexo); + const n: (...args: OriginalParams) => OriginalReturn = newConsole.bind(hexo); const post = hexo.post; const now = Date.now(); let clock; @@ -45,9 +46,9 @@ describe('new', () => { await n({ _: [] }); - hexo.call.calledOnce.should.be.true; - hexo.call.args[0][0].should.eql('help'); - hexo.call.args[0][1]._[0].should.eql('new'); + (hexo.call as SinonSpy).calledOnce.should.be.true; + (hexo.call as SinonSpy).args[0][0].should.eql('help'); + (hexo.call as SinonSpy).args[0][1]._[0].should.eql('new'); }); it('title', async () => { diff --git a/test/scripts/console/publish.js b/test/scripts/console/publish.ts similarity index 76% rename from test/scripts/console/publish.js rename to test/scripts/console/publish.ts index 44069af45e..afd2dcef7d 100644 --- a/test/scripts/console/publish.js +++ b/test/scripts/console/publish.ts @@ -1,18 +1,20 @@ -'use strict'; - -const { exists, mkdirs, readFile, rmdir, unlink } = require('hexo-fs'); -const moment = require('moment'); -const { join } = require('path'); -const Promise = require('bluebird'); -const { useFakeTimers, spy } = require('sinon'); +import { exists, mkdirs, readFile, rmdir, unlink } from 'hexo-fs'; +import moment from 'moment'; +import { join } from 'path'; +// @ts-ignore +import Promise from 'bluebird'; +import { useFakeTimers, spy, SinonSpy, SinonFakeTimers } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import publishConsole from '../../../lib/plugins/console/publish'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('publish', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'publish_test'), {silent: true}); - const publish = require('../../../dist/plugins/console/publish').bind(hexo); + const publish: (...args: OriginalParams) => OriginalReturn = publishConsole.bind(hexo); const post = hexo.post; const now = Date.now(); - let clock; + let clock: SinonFakeTimers; before(async () => { clock = useFakeTimers(now); @@ -73,13 +75,13 @@ describe('publish', () => { it('no args', async () => { const hexo = new Hexo(join(__dirname, 'publish_test'), {silent: true}); hexo.call = spy(); - const publish = require('../../../dist/plugins/console/publish').bind(hexo); + const publish: (...args: OriginalParams) => OriginalReturn = publishConsole.bind(hexo); await publish({_: []}); - hexo.call.calledOnce.should.be.true; - hexo.call.args[0][0].should.eql('help'); - hexo.call.args[0][1]._[0].should.eql('publish'); + (hexo.call as SinonSpy).calledOnce.should.be.true; + (hexo.call as SinonSpy).args[0][0].should.eql('help'); + (hexo.call as SinonSpy).args[0][1]._[0].should.eql('publish'); }); it('layout', async () => { diff --git a/test/scripts/console/render.js b/test/scripts/console/render.ts similarity index 72% rename from test/scripts/console/render.js rename to test/scripts/console/render.ts index 1a611766c8..d79ef572e1 100644 --- a/test/scripts/console/render.js +++ b/test/scripts/console/render.ts @@ -1,14 +1,16 @@ -'use strict'; - -const { mkdirs, readFile, rmdir, unlink, writeFile } = require('hexo-fs'); -const { join } = require('path'); -const Promise = require('bluebird'); -const { spy } = require('sinon'); +import { mkdirs, readFile, rmdir, unlink, writeFile } from 'hexo-fs'; +import { join } from 'path'; +// @ts-ignore +import Promise from 'bluebird'; +import { spy, SinonSpy } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import renderConsole from '../../../lib/plugins/console/render'; +type OriginalParams = Parameters; +type OriginalReturn = ReturnType; describe('render', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'render_test'), {silent: true}); - const render = require('../../../dist/plugins/console/render').bind(hexo); + const render: (...args: OriginalParams) => OriginalReturn = renderConsole.bind(hexo); before(async () => { await mkdirs(hexo.base_dir); @@ -26,13 +28,13 @@ describe('render', () => { it('no args', async () => { const hexo = new Hexo(join(__dirname, 'render_test'), {silent: true}); hexo.call = spy(); - const render = require('../../../dist/plugins/console/render').bind(hexo); + const render: (...args: OriginalParams) => OriginalReturn = renderConsole.bind(hexo); await render({_: []}); - hexo.call.calledOnce.should.be.true; - hexo.call.args[0][0].should.eql('help'); - hexo.call.args[0][1]._.should.eql('render'); + (hexo.call as SinonSpy).calledOnce.should.be.true; + (hexo.call as SinonSpy).args[0][0].should.eql('help'); + (hexo.call as SinonSpy).args[0][1]._.should.eql('render'); }); it('relative path', async () => { @@ -41,7 +43,7 @@ describe('render', () => { await writeFile(src, body); await render({_: ['test.yml'], output: 'result.json'}); - const result = await readFile(dest); + const result = await readFile(dest) as string; JSON.parse(result).should.eql({ foo: 1, bar: { @@ -62,7 +64,7 @@ describe('render', () => { await writeFile(src, body); await render({_: [src], output: 'result.json'}); - const result = await readFile(dest); + const result = await readFile(dest) as string; JSON.parse(result).should.eql({ foo: 1, bar: { @@ -83,7 +85,7 @@ describe('render', () => { await writeFile(src, body); await render({_: ['test.yml'], output: dest}); - const result = await readFile(dest); + const result = await readFile(dest) as string; JSON.parse(result).should.eql({ foo: 1, bar: { @@ -106,7 +108,7 @@ describe('render', () => { await writeFile(src, body); await render({_: ['test'], output: 'result.json', engine: 'yaml'}); - const result = await readFile(dest); + const result = await readFile(dest) as string; JSON.parse(result).should.eql({ foo: 1, bar: { diff --git a/test/scripts/extend/console.js b/test/scripts/extend/console.ts similarity index 82% rename from test/scripts/extend/console.js rename to test/scripts/extend/console.ts index 479937d687..ab70d3d04a 100644 --- a/test/scripts/extend/console.js +++ b/test/scripts/extend/console.ts @@ -1,12 +1,13 @@ -'use strict'; +import Console from '../../../lib/extend/console'; +import chai from 'chai'; +const should = chai.should(); describe('Console', () => { - const Console = require('../../../dist/extend/console'); - it('register()', () => { const c = new Console(); // no name + // @ts-ignore should.throw(() => c.register(), TypeError, 'name is required'); // name, fn @@ -15,31 +16,35 @@ describe('Console', () => { c.get('test').should.exist; // name, not fn + // @ts-ignore should.throw(() => c.register('test'), TypeError, 'fn must be a function'); // name, desc, fn c.register('test', 'this is a test', () => {}); c.get('test').should.exist; + // @ts-ignore c.get('test').desc.should.eql('this is a test'); // name, desc, not fn + // @ts-ignore should.throw(() => c.register('test', 'this is a test'), TypeError, 'fn must be a function'); // name, options, fn c.register('test', {init: true}, () => {}); c.get('test').should.exist; - c.get('test').options.init.should.be.true; + c.get('test').options!.init!.should.be.true; // name, desc, options, fn c.register('test', 'this is a test', {init: true}, () => {}); c.get('test').should.exist; - c.get('test').desc.should.eql('this is a test'); - c.get('test').options.init.should.be.true; + c.get('test').desc!.should.eql('this is a test'); + c.get('test').options!.init!.should.be.true; // name, desc, options, not fn + // @ts-ignore should.throw(() => c.register('test', 'this is a test', {init: true}), TypeError, 'fn must be a function'); }); @@ -61,10 +66,11 @@ describe('Console', () => { c.register('test', (args, callback) => { args.should.eql({foo: 'bar'}); - callback(null, 'foo'); + callback && callback(null, 'foo'); }); c.get('test')({ + _: [], foo: 'bar' }).then(result => { result.should.eql('foo'); diff --git a/test/scripts/extend/deployer.js b/test/scripts/extend/deployer.ts similarity index 84% rename from test/scripts/extend/deployer.js rename to test/scripts/extend/deployer.ts index 7318cc9777..fc5d096cd2 100644 --- a/test/scripts/extend/deployer.js +++ b/test/scripts/extend/deployer.ts @@ -1,8 +1,8 @@ -'use strict'; +import Deployer from '../../../lib/extend/deployer'; +import chai from 'chai'; +const should = chai.should(); describe('Deployer', () => { - const Deployer = require('../../../dist/extend/deployer'); - it('register()', () => { const d = new Deployer(); @@ -12,9 +12,11 @@ describe('Deployer', () => { d.get('test').should.exist; // no name + // @ts-ignore should.throw(() => d.register(), TypeError, 'name is required'); // no fn + // @ts-ignore should.throw(() => d.register('test'), TypeError, 'fn must be a function'); }); @@ -23,10 +25,11 @@ describe('Deployer', () => { d.register('test', (args, callback) => { args.should.eql({foo: 'bar'}); - callback(null, 'foo'); + callback && callback(null, 'foo'); }); d.get('test')({ + type: '', foo: 'bar' }).then(result => { result.should.eql('foo'); @@ -42,6 +45,7 @@ describe('Deployer', () => { }); d.get('test')({ + type: '', foo: 'bar' }).then(result => { result.should.eql('foo'); diff --git a/test/scripts/extend/filter.js b/test/scripts/extend/filter.ts similarity index 92% rename from test/scripts/extend/filter.js rename to test/scripts/extend/filter.ts index 6010ce5bc6..a7f5adf0f0 100644 --- a/test/scripts/extend/filter.js +++ b/test/scripts/extend/filter.ts @@ -1,10 +1,9 @@ -'use strict'; - -const { spy } = require('sinon'); +import Filter from '../../../lib/extend/filter'; +import { spy } from 'sinon'; +import chai from 'chai'; +const should = chai.should(); describe('Filter', () => { - const Filter = require('../../../dist/extend/filter'); - it('register()', () => { const f = new Filter(); @@ -12,25 +11,26 @@ describe('Filter', () => { f.register('test', () => {}); f.list('test')[0].should.exist; - f.list('test')[0].priority.should.eql(10); + f.list('test')[0].priority!.should.eql(10); // type, fn, priority f.register('test2', () => {}, 50); - f.list('test2')[0].priority.should.eql(50); + f.list('test2')[0].priority!.should.eql(50); // fn f.register(() => {}); f.list('after_post_render')[0].should.exist; - f.list('after_post_render')[0].priority.should.eql(10); + f.list('after_post_render')[0].priority!.should.eql(10); // fn, priority f.register(() => {}, 50); - f.list('after_post_render')[1].priority.should.eql(50); + f.list('after_post_render')[1].priority!.should.eql(50); // no fn + // @ts-ignore should.throw(() => f.register(), TypeError, 'fn must be a function'); }); @@ -67,17 +67,19 @@ describe('Filter', () => { f.register('test', filter); f.unregister('test', filter); - await f.exec('test'); + await f.exec('test', ''); filter.called.should.be.false; }); it('unregister() - type is required', () => { const f = new Filter(); + // @ts-ignore should.throw(() => f.unregister(), 'type is required'); }); it('unregister() - fn must be a function', () => { const f = new Filter(); + // @ts-ignore should.throw(() => f.unregister('test'), 'fn must be a function'); }); diff --git a/test/scripts/extend/generator.js b/test/scripts/extend/generator.ts similarity index 60% rename from test/scripts/extend/generator.js rename to test/scripts/extend/generator.ts index d90b295fd1..37325838b6 100644 --- a/test/scripts/extend/generator.js +++ b/test/scripts/extend/generator.ts @@ -1,40 +1,42 @@ -'use strict'; +import Generator from '../../../lib/extend/generator'; +import chai from 'chai'; +const should = chai.should(); describe('Generator', () => { - const Generator = require('../../../dist/extend/generator'); - it('register()', () => { const g = new Generator(); // name, fn - g.register('test', () => {}); + g.register('test', () => []); g.get('test').should.exist; // fn - g.register(() => {}); + g.register(() => []); g.get('generator-0').should.exist; // no fn + // @ts-ignore should.throw(() => g.register('test'), TypeError, 'fn must be a function'); }); it('register() - promisify', async () => { const g = new Generator(); - g.register('test', (locals, render, callback) => { - callback(null, 'foo'); + g.register('test', (_locals, callback) => { + callback && callback(null, 'foo'); + return []; }); - const result = await g.get('test')({}, {}); + const result = await g.get('test')({}); result.should.eql('foo'); }); it('get()', () => { const g = new Generator(); - g.register('test', () => {}); + g.register('test', () => []); g.get('test').should.exist; }); @@ -42,7 +44,7 @@ describe('Generator', () => { it('list()', () => { const g = new Generator(); - g.register('test', () => {}); + g.register('test', () => []); g.list().should.have.all.keys(['test']); }); diff --git a/test/scripts/extend/helper.js b/test/scripts/extend/helper.ts similarity index 68% rename from test/scripts/extend/helper.js rename to test/scripts/extend/helper.ts index 30054f1a4b..2bb5152c66 100644 --- a/test/scripts/extend/helper.js +++ b/test/scripts/extend/helper.ts @@ -1,27 +1,29 @@ -'use strict'; +import Helper from '../../../lib/extend/helper'; +import chai from 'chai'; +const should = chai.should(); describe('Helper', () => { - const Helper = require('../../../dist/extend/helper'); - it('register()', () => { const h = new Helper(); // name, fn - h.register('test', () => {}); + h.register('test', () => ''); h.get('test').should.exist; // no fn + // @ts-ignore should.throw(() => h.register('test'), TypeError, 'fn must be a function'); // no name + // @ts-ignore should.throw(() => h.register(), TypeError, 'name is required'); }); it('list()', () => { const h = new Helper(); - h.register('test', () => {}); + h.register('test', () => ''); h.list().should.have.all.keys(['test']); }); @@ -29,7 +31,7 @@ describe('Helper', () => { it('get()', () => { const h = new Helper(); - h.register('test', () => {}); + h.register('test', () => ''); h.get('test').should.exist; }); diff --git a/test/scripts/extend/index.js b/test/scripts/extend/index.js deleted file mode 100644 index dbd1e467ef..0000000000 --- a/test/scripts/extend/index.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -describe('Extend', () => { - require('./console'); - require('./deployer'); - require('./filter'); - require('./generator'); - require('./helper'); - require('./injector'); - require('./migrator'); - require('./processor'); - require('./renderer'); - require('./tag'); - require('./tag_errors'); -}); diff --git a/test/scripts/extend/injector.js b/test/scripts/extend/injector.ts similarity index 99% rename from test/scripts/extend/injector.js rename to test/scripts/extend/injector.ts index d82c035607..24d7c2106e 100644 --- a/test/scripts/extend/injector.js +++ b/test/scripts/extend/injector.ts @@ -1,4 +1,4 @@ -'use strict'; +import Injector from '../../../lib/extend/injector'; describe('Injector', () => { const content = [ @@ -13,13 +13,12 @@ describe('Injector', () => { '' ].join(''); - const Injector = require('../../../dist/extend/injector'); - it('register() - entry is required', () => { const i = new Injector(); // no name try { + // @ts-ignore i.register(); } catch (err) { err.should.be @@ -53,6 +52,7 @@ describe('Injector', () => { const i = new Injector(); const str = ''; + // @ts-ignore i.register('foo', str); i.get('head_end').should.contains(str); diff --git a/test/scripts/extend/migrator.js b/test/scripts/extend/migrator.ts similarity index 86% rename from test/scripts/extend/migrator.js rename to test/scripts/extend/migrator.ts index fe045b3c28..a284e04dae 100644 --- a/test/scripts/extend/migrator.js +++ b/test/scripts/extend/migrator.ts @@ -1,8 +1,8 @@ -'use strict'; +import Migrator from '../../../lib/extend/migrator'; +import chai from 'chai'; +const should = chai.should(); describe('Migrator', () => { - const Migrator = require('../../../dist/extend/migrator'); - it('register()', () => { const d = new Migrator(); @@ -12,9 +12,11 @@ describe('Migrator', () => { d.get('test').should.exist; // no name + // @ts-ignore should.throw(() => d.register(), TypeError, 'name is required'); // no fn + // @ts-ignore should.throw(() => d.register('test'), TypeError, 'fn must be a function'); }); @@ -23,7 +25,7 @@ describe('Migrator', () => { d.register('test', (args, callback) => { args.should.eql({foo: 'bar'}); - callback(null, 'foo'); + callback && callback(null, 'foo'); }); d.get('test')({ diff --git a/test/scripts/extend/processor.js b/test/scripts/extend/processor.ts similarity index 79% rename from test/scripts/extend/processor.js rename to test/scripts/extend/processor.ts index 1d9cb12407..0a2e5236a8 100644 --- a/test/scripts/extend/processor.js +++ b/test/scripts/extend/processor.ts @@ -1,8 +1,8 @@ -'use strict'; +import Processor from '../../../lib/extend/processor'; +import chai from 'chai'; +const should = chai.should(); describe('Processor', () => { - const Processor = require('../../../dist/extend/processor'); - it('register()', () => { const p = new Processor(); @@ -17,11 +17,13 @@ describe('Processor', () => { p.list()[1].should.exist; // more than one arg + // @ts-ignore p.register((a, b) => {}); p.list()[1].should.exist; // no fn + // @ts-ignore should.throw(() => p.register(), TypeError, 'fn must be a function'); }); diff --git a/test/scripts/extend/renderer.js b/test/scripts/extend/renderer.ts similarity index 72% rename from test/scripts/extend/renderer.js rename to test/scripts/extend/renderer.ts index 8cb8131251..f06dd2cbdd 100644 --- a/test/scripts/extend/renderer.js +++ b/test/scripts/extend/renderer.ts @@ -1,32 +1,38 @@ -'use strict'; +import Renderer from '../../../lib/extend/renderer'; +// @ts-ignore +import Promise from 'bluebird'; +import chai from 'chai'; +const should = chai.should(); describe('Renderer', () => { - const Renderer = require('../../../dist/extend/renderer').default; it('register()', () => { const r = new Renderer(); // name, output, fn - r.register('yaml', 'json', () => {}); + r.register('yaml', 'json', () => Promise.resolve()); r.get('yaml').should.exist; - r.get('yaml').output.should.eql('json'); + r.get('yaml').output!.should.eql('json'); // name, output, fn, sync r.register('yaml', 'json', () => {}, true); r.get('yaml').should.exist; - r.get('yaml').output.should.eql('json'); + r.get('yaml').output!.should.eql('json'); r.get('yaml', true).should.exist; - r.get('yaml', true).output.should.eql('json'); + r.get('yaml', true).output!.should.eql('json'); // no fn + // @ts-ignore should.throw(() => r.register('yaml', 'json'), TypeError, 'fn must be a function'); // no output + // @ts-ignore should.throw(() => r.register('yaml'), TypeError, 'output is required'); // no name + // @ts-ignore should.throw(() => r.register(), TypeError, 'name is required'); }); @@ -34,8 +40,9 @@ describe('Renderer', () => { const r = new Renderer(); // async - r.register('yaml', 'json', (data, options, callback) => { - callback(null, 'foo'); + r.register('yaml', 'json', (_data, _options, callback) => { + callback && callback(null, 'foo'); + return Promise.resolve(); }); const yaml = await r.get('yaml')({}, {}); @@ -51,20 +58,22 @@ describe('Renderer', () => { it('register() - compile', () => { const r = new Renderer(); - function renderer(data, locals) {} + function renderer(data, locals) { + return Promise.resolve(); + } renderer.compile = data => { // }; r.register('swig', 'html', renderer); - r.get('swig').compile.should.eql(renderer.compile); + r.get('swig').compile!.should.eql(renderer.compile); }); it('getOutput()', () => { const r = new Renderer(); - r.register('yaml', 'json', () => {}); + r.register('yaml', 'json', () => Promise.resolve()); r.getOutput('yaml').should.eql('json'); r.getOutput('.yaml').should.eql('json'); @@ -75,7 +84,7 @@ describe('Renderer', () => { it('isRenderable()', () => { const r = new Renderer(); - r.register('yaml', 'json', () => {}); + r.register('yaml', 'json', () => Promise.resolve()); r.isRenderable('yaml').should.be.true; r.isRenderable('.yaml').should.be.true; @@ -86,7 +95,7 @@ describe('Renderer', () => { it('isRenderableSync()', () => { const r = new Renderer(); - r.register('yaml', 'json', () => {}); + r.register('yaml', 'json', () => Promise.resolve()); r.isRenderableSync('yaml').should.be.false; @@ -101,7 +110,7 @@ describe('Renderer', () => { it('get()', () => { const r = new Renderer(); - r.register('yaml', 'json', () => {}); + r.register('yaml', 'json', () => Promise.resolve()); r.get('yaml').should.exist; r.get('.yaml').should.exist; @@ -118,7 +127,7 @@ describe('Renderer', () => { it('list()', () => { const r = new Renderer(); - r.register('yaml', 'json', () => {}); + r.register('yaml', 'json', () => Promise.resolve()); r.register('swig', 'html', () => {}, true); diff --git a/test/scripts/extend/tag.js b/test/scripts/extend/tag.ts similarity index 93% rename from test/scripts/extend/tag.js rename to test/scripts/extend/tag.ts index 8f10573af1..cad5876d18 100644 --- a/test/scripts/extend/tag.js +++ b/test/scripts/extend/tag.ts @@ -1,7 +1,8 @@ -'use strict'; +import Tag from '../../../lib/extend/tag'; +import chai from 'chai'; +const should = chai.should(); describe('Tag', () => { - const Tag = require('../../../dist/extend/tag'); const tag = new Tag(); it('register()', async () => { @@ -112,8 +113,9 @@ describe('Tag', () => { it('register() - async callback', async () => { const tag = new Tag(); - tag.register('test', (args, content, callback) => { - callback(null, args.join(' ')); + tag.register('test', async (args, content, callback) => { + callback && callback(null, args.join(' ')); + return ''; }, { async: true }); const result = await tag.render('{% test foo bar %}'); @@ -121,10 +123,12 @@ describe('Tag', () => { }); it('register() - name is required', () => { + // @ts-ignore should.throw(() => tag.register(), 'name is required'); }); it('register() - fn must be a function', () => { + // @ts-ignore should.throw(() => tag.register('test'), 'fn must be a function'); }); @@ -145,6 +149,7 @@ describe('Tag', () => { }); it('unregister() - name is required', () => { + // @ts-ignore should.throw(() => tag.unregister(), 'name is required'); }); diff --git a/test/scripts/extend/tag_errors.js b/test/scripts/extend/tag_errors.ts similarity index 92% rename from test/scripts/extend/tag_errors.js rename to test/scripts/extend/tag_errors.ts index 3184d8a09d..03e4704f19 100644 --- a/test/scripts/extend/tag_errors.js +++ b/test/scripts/extend/tag_errors.ts @@ -1,8 +1,6 @@ -'use strict'; +import Tag from '../../../lib/extend/tag'; describe('Tag Errors', () => { - const Tag = require('../../../dist/extend/tag'); - const assertNunjucksError = (err, line, type) => { err.should.have.property('name', 'Nunjucks Error'); err.should.have.property('message'); @@ -30,7 +28,7 @@ describe('Tag Errors', () => { const tag = new Tag(); tag.register('test', - (args, content) => {}, + (args, content) => { return ''; }, { ends: true }); const body = [ @@ -51,7 +49,7 @@ describe('Tag Errors', () => { const tag = new Tag(); tag.register('test', - (args, content) => {}, + (args, content) => { return ''; }, { ends: true }); const body = [ @@ -87,7 +85,7 @@ describe('Tag Errors', () => { const tag = new Tag(); tag.register('test', - (args, content) => {}, + (args, content) => { return ''; }, { ends: true }); const body = [ @@ -108,7 +106,7 @@ describe('Tag Errors', () => { const tag = new Tag(); tag.register('test', - (args, content) => {}, + (args, content) => { return ''; }, { ends: true }); const body = [ @@ -130,7 +128,7 @@ describe('Tag Errors', () => { const tag = new Tag(); tag.register('test', - (args, content) => {}, + (args, content) => { return ''; }, { ends: true }); const body = [ diff --git a/test/scripts/filters/backtick_code_block.js b/test/scripts/filters/backtick_code_block.ts similarity index 95% rename from test/scripts/filters/backtick_code_block.js rename to test/scripts/filters/backtick_code_block.ts index 5c75bbccdb..0dce3c3465 100644 --- a/test/scripts/filters/backtick_code_block.js +++ b/test/scripts/filters/backtick_code_block.ts @@ -1,13 +1,14 @@ -'use strict'; - -const util = require('hexo-util'); -const defaultConfig = require('../../../dist/hexo/default_config'); +import { highlight as highlightJs, prismHighlight, escapeHTML } from 'hexo-util'; +import defaultConfig from '../../../lib/hexo/default_config'; +import Hexo from '../../../lib/hexo'; +import defaultCodeBlock from '../../../lib/plugins/filter/before_post_render/backtick_code_block'; +import chai from 'chai'; +const should = chai.should(); describe('Backtick code block', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - require('../../../dist/plugins/highlight/')(hexo); - const codeBlock = require('../../../dist/plugins/filter/before_post_render/backtick_code_block')(hexo); + require('../../../lib/plugins/highlight/')(hexo); + const codeBlock = defaultCodeBlock(hexo); const code = [ 'if (tired && night) {', @@ -15,14 +16,14 @@ describe('Backtick code block', () => { '}' ].join('\n'); - function highlight(code, options) { - return util.highlight(code, options || {}) + function highlight(code: string, options?) { + return highlightJs(code, options || {}) .replace(/{/g, '{') .replace(/}/g, '}'); } - function prism(code, options) { - return util.prismHighlight(code, options || {}) + function prism(code: string, options?) { + return prismHighlight(code, options || {}) .replace(/{/g, '{') .replace(/}/g, '}'); } @@ -64,7 +65,9 @@ describe('Backtick code block', () => { const oldHljsCfg = hexo.config.highlight; const oldPrismCfg = hexo.config.prismjs; + // @ts-ignore delete hexo.config.highlight; + // @ts-ignore delete hexo.config.prismjs; codeBlock(data); @@ -646,7 +649,7 @@ describe('Backtick code block', () => { ].join('\n') }; const escapeSwigTag = str => str.replace(/{/g, '{').replace(/}/g, '}'); - const expected = `
${escapeSwigTag(util.escapeHTML(code))}
`; + const expected = `
${escapeSwigTag(escapeHTML(code))}
`; codeBlock(data); data.content.should.eql('' + expected + ''); }); diff --git a/test/scripts/filters/excerpt.js b/test/scripts/filters/excerpt.ts similarity index 65% rename from test/scripts/filters/excerpt.js rename to test/scripts/filters/excerpt.ts index c45bd7f757..88175d2c1d 100644 --- a/test/scripts/filters/excerpt.js +++ b/test/scripts/filters/excerpt.ts @@ -1,9 +1,11 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import excerptFilter from '../../../lib/plugins/filter/after_post_render/excerpt'; +type ExcerptFilterParams = Parameters; +type ExcerptFilterReturn = ReturnType; describe('Excerpt', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const excerpt = require('../../../dist/plugins/filter/after_post_render/excerpt').bind(hexo); + const excerpt: (...args: ExcerptFilterParams) => ExcerptFilterReturn = excerptFilter.bind(hexo); it('without ', () => { const content = [ @@ -12,14 +14,18 @@ describe('Excerpt', () => { 'baz' ].join('\n'); - const data = { + const data: { + content: string; + excerpt?: string; + more?: string; + } = { content }; excerpt(data); data.content.should.eql(content); - data.excerpt.should.eql(''); - data.more.should.eql(content); + data.excerpt!.should.eql(''); + data.more!.should.eql(content); }); it('with ', () => { @@ -40,7 +46,11 @@ describe('Excerpt', () => { 'baz' ].join('\n'); - const data = { + const data: { + content: string; + excerpt?: string; + more?: string; + } = { content }; @@ -53,12 +63,12 @@ describe('Excerpt', () => { 'baz' ].join('\n')); - data.excerpt.should.eql([ + data.excerpt!.should.eql([ 'foo', 'bar' ].join('\n')); - data.more.should.eql([ + data.more!.should.eql([ 'baz' ].join('\n')); } @@ -73,7 +83,11 @@ describe('Excerpt', () => { 'baz' ].join('\n'); - const data = { + const data: { + content: string; + excerpt?: string; + more?: string; + } = { content }; @@ -87,11 +101,11 @@ describe('Excerpt', () => { 'baz' ].join('\n')); - data.excerpt.should.eql([ + data.excerpt!.should.eql([ 'foo' ].join('\n')); - data.more.should.eql([ + data.more!.should.eql([ 'bar', '', 'baz' @@ -105,7 +119,11 @@ describe('Excerpt', () => { 'bar' ].join('\n'); - const data = { + const data: { + content: string; + excerpt: string; + more?: string; + } = { content, excerpt: 'baz' }; @@ -122,7 +140,7 @@ describe('Excerpt', () => { 'baz' ].join('\n')); - data.more.should.eql([ + data.more!.should.eql([ 'foo', '', 'bar' diff --git a/test/scripts/filters/external_link.js b/test/scripts/filters/external_link.ts similarity index 89% rename from test/scripts/filters/external_link.js rename to test/scripts/filters/external_link.ts index dbec1dbca5..414168593c 100644 --- a/test/scripts/filters/external_link.js +++ b/test/scripts/filters/external_link.ts @@ -1,17 +1,22 @@ -'use strict'; - -const decache = require('decache'); +import Hexo from '../../../lib/hexo'; +import decache from 'decache'; +import externalLinkFilter from '../../../lib/plugins/filter/after_render/external_link'; +import externalLinkPostFilter from '../../../lib/plugins/filter/after_post_render/external_link'; +import chai from 'chai'; +const should = chai.should(); +type ExternalLinkParams = Parameters; +type ExternalLinkReturn = ReturnType; +type ExternalLinkPostParams = Parameters; +type ExternalLinkPostReturn = ReturnType; describe('External link', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - let externalLink; + let externalLink: (...args: ExternalLinkParams) => ExternalLinkReturn; beforeEach(() => { - decache('../../../dist/plugins/filter/after_render/external_link'); - externalLink = require('../../../dist/plugins/filter/after_render/external_link').bind(hexo); + decache('../../../lib/plugins/filter/after_render/external_link'); + externalLink = require('../../../lib/plugins/filter/after_render/external_link').bind(hexo); }); - hexo.config = { url: 'https://example.com', external_link: { @@ -19,7 +24,7 @@ describe('External link', () => { field: 'site', exclude: '' } - }; + } as any; it('disabled', () => { const content = 'foo' @@ -122,6 +127,7 @@ describe('External link', () => { 'Hexo' ].join('\n'); + // @ts-ignore hexo.config.external_link.exclude = ['foo.com', 'bar.com']; const result = externalLink(content); @@ -137,14 +143,14 @@ describe('External link', () => { }); describe('External link - post', () => { - const Hexo = require('../../../dist/hexo'); + const Hexo = require('../../../lib/hexo'); const hexo = new Hexo(); - let externalLink; + let externalLink: (...args: ExternalLinkPostParams) => ExternalLinkPostReturn; beforeEach(() => { - decache('../../../dist/plugins/filter/after_post_render/external_link'); - externalLink = require('../../../dist/plugins/filter/after_post_render/external_link').bind(hexo); + decache('../../../lib/plugins/filter/after_post_render/external_link'); + externalLink = require('../../../lib/plugins/filter/after_post_render/external_link').bind(hexo); }); hexo.config = { diff --git a/test/scripts/filters/i18n_locals.js b/test/scripts/filters/i18n_locals.ts similarity index 83% rename from test/scripts/filters/i18n_locals.js rename to test/scripts/filters/i18n_locals.ts index 6ac2f920dc..acbab46463 100644 --- a/test/scripts/filters/i18n_locals.js +++ b/test/scripts/filters/i18n_locals.ts @@ -1,9 +1,11 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import i18nLocalsFilter from '../../../lib/plugins/filter/template_locals/i18n'; +type I18nLocalsFilterParams = Parameters; +type I18nLocalsFilterReturn = ReturnType; describe('i18n locals', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const i18nFilter = require('../../../dist/plugins/filter/template_locals/i18n').bind(hexo); + const i18nFilter: (...args: I18nLocalsFilterParams) => I18nLocalsFilterReturn = i18nLocalsFilter.bind(hexo); const theme = hexo.theme; const i18n = theme.i18n; @@ -33,7 +35,7 @@ describe('i18n locals', () => { page: { lang: 'zh-tw' } - }; + } as any; i18nFilter(locals); @@ -46,7 +48,7 @@ describe('i18n locals', () => { page: { language: 'zh-tw' } - }; + } as any; i18nFilter(locals); @@ -56,9 +58,9 @@ describe('i18n locals', () => { it('detect by path (lang found)', () => { const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'zh-tw/index.html' - }; + } as any; i18nFilter(locals); @@ -70,9 +72,9 @@ describe('i18n locals', () => { it('detect by path (lang not found)', () => { const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'news/index.html' - }; + } as any; i18nFilter(locals); @@ -84,9 +86,9 @@ describe('i18n locals', () => { it('use config by default', () => { const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'index.html' - }; + } as any; i18nFilter(locals); @@ -101,9 +103,9 @@ describe('i18n locals', () => { const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'index.html' - }; + } as any; i18nFilter(locals); @@ -115,14 +117,14 @@ describe('i18n locals', () => { }); it('use config by default - with no languages, default language should be used', () => { - const oldConfig = i18n.language; + const oldConfig = i18n.languages; i18n.languages = ['default']; const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'index.html' - }; + } as any; i18nFilter(locals); @@ -139,9 +141,9 @@ describe('i18n locals', () => { const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'index.html' - }; + } as any; i18nFilter(locals); @@ -160,9 +162,9 @@ describe('i18n locals', () => { const locals = { config: hexo.config, - page: {}, + page: {} as any, path: 'index.html' - }; + } as any; i18nFilter(locals); diff --git a/test/scripts/filters/index.js b/test/scripts/filters/index.js deleted file mode 100644 index d899acf7b1..0000000000 --- a/test/scripts/filters/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -describe('Filters', () => { - require('./backtick_code_block'); - require('./excerpt'); - require('./external_link'); - require('./i18n_locals'); - require('./meta_generator'); - require('./new_post_path'); - require('./post_permalink'); - require('./render_post'); - require('./save_database'); - require('./titlecase'); -}); diff --git a/test/scripts/filters/meta_generator.js b/test/scripts/filters/meta_generator.ts similarity index 61% rename from test/scripts/filters/meta_generator.js rename to test/scripts/filters/meta_generator.ts index f87bcc000b..66aa8cdc5b 100644 --- a/test/scripts/filters/meta_generator.js +++ b/test/scripts/filters/meta_generator.ts @@ -1,16 +1,19 @@ -'use strict'; - -const decache = require('decache'); +import Hexo from '../../../lib/hexo'; +import decache from 'decache'; +import cheerio from 'cheerio'; +import type hexoMetaGeneratorInject from '../../../lib/plugins/filter/after_render/meta_generator'; +import chai from 'chai'; +const should = chai.should(); +type hexoMetaGeneratorInjectParams = Parameters; +type hexoMetaGeneratorInjectReturn = ReturnType; describe('Meta Generator', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - let metaGenerator; - const cheerio = require('cheerio'); + let metaGenerator: (...args: hexoMetaGeneratorInjectParams) => hexoMetaGeneratorInjectReturn; beforeEach(() => { - decache('../../../dist/plugins/filter/after_render/meta_generator'); - metaGenerator = require('../../../dist/plugins/filter/after_render/meta_generator').bind(hexo); + decache('../../../lib/plugins/filter/after_render/meta_generator'); + metaGenerator = require('../../../lib/plugins/filter/after_render/meta_generator').bind(hexo); }); it('default', () => { @@ -19,7 +22,7 @@ describe('Meta Generator', () => { const $ = cheerio.load(result); $('meta[name="generator"]').should.have.lengthOf(1); - $('meta[name="generator"]').attr('content').should.eql(`Hexo ${hexo.version}`); + $('meta[name="generator"]').attr('content')!.should.eql(`Hexo ${hexo.version}`); }); it('disable meta_generator', () => { diff --git a/test/scripts/filters/new_post_path.js b/test/scripts/filters/new_post_path.ts similarity index 86% rename from test/scripts/filters/new_post_path.js rename to test/scripts/filters/new_post_path.ts index 006c973538..13cef2cba6 100644 --- a/test/scripts/filters/new_post_path.js +++ b/test/scripts/filters/new_post_path.ts @@ -1,14 +1,15 @@ -'use strict'; - -const { join } = require('path'); -const moment = require('moment'); -const { createSha1Hash } = require('hexo-util'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); +import { join } from 'path'; +import moment from 'moment'; +import { createSha1Hash } from 'hexo-util'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import newPostPathFilter from '../../../lib/plugins/filter/new_post_path'; +type NewPostPathFilterParams = Parameters; +type NewPostPathFilterReturn = ReturnType; describe('new_post_path', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'new_post_path_test')); - const newPostPath = require('../../../dist/plugins/filter/new_post_path').bind(hexo); + const newPostPath: (...args: NewPostPathFilterParams) => NewPostPathFilterReturn = newPostPathFilter.bind(hexo); const sourceDir = hexo.source_dir; const draftDir = join(sourceDir, '_drafts'); const postDir = join(sourceDir, '_posts'); @@ -77,7 +78,7 @@ describe('new_post_path', () => { const target = await newPostPath({ slug: 'foo', - date: date.toDate() + date: date.toDate() as any }); target.should.eql(join(postDir, date.format('YYYY-M-D') + '-foo.md')); }); @@ -113,7 +114,7 @@ describe('new_post_path', () => { const target = await newPostPath({ slug, title: 'tree', - date: now.format('YYYY-MM-DD HH:mm:ss') + date: now.format('YYYY-MM-DD HH:mm:ss') as any }); target.should.eql(join(postDir, `${slug}-${hash}.md`)); diff --git a/test/scripts/filters/post_permalink.js b/test/scripts/filters/post_permalink.ts similarity index 93% rename from test/scripts/filters/post_permalink.js rename to test/scripts/filters/post_permalink.ts index 3643ed752f..dd530ab090 100644 --- a/test/scripts/filters/post_permalink.js +++ b/test/scripts/filters/post_permalink.ts @@ -1,11 +1,12 @@ -'use strict'; - -const moment = require('moment'); +import moment from 'moment'; +import Hexo from '../../../lib/hexo'; +import postPermalinkFilter from '../../../lib/plugins/filter/post_permalink'; +type PostPermalinkFilterParams = Parameters; +type PostPermalinkFilterReturn = ReturnType; describe('post_permalink', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const postPermalink = require('../../../dist/plugins/filter/post_permalink').bind(hexo); + const postPermalink: (...args: PostPermalinkFilterParams) => PostPermalinkFilterReturn = postPermalinkFilter.bind(hexo); const Post = hexo.model('Post'); let post; @@ -130,7 +131,7 @@ describe('post_permalink', () => { it('permalink_defaults - null', async () => { hexo.config.permalink = 'posts/:lang/:title/'; - hexo.config.permalink_defaults = null; + hexo.config.permalink_defaults = null as any; const posts = await Post.insert([{ source: 'my-new-post.md', diff --git a/test/scripts/filters/render_post.js b/test/scripts/filters/render_post.ts similarity index 65% rename from test/scripts/filters/render_post.js rename to test/scripts/filters/render_post.ts index e5540cc7e4..f60252d2fa 100644 --- a/test/scripts/filters/render_post.js +++ b/test/scripts/filters/render_post.ts @@ -1,13 +1,14 @@ -'use strict'; - -const { content, expected } = require('../../fixtures/post_render'); +import Hexo from '../../../lib/hexo'; +import renderPostFilter from '../../../lib/plugins/filter/before_generate/render_post'; +import { content, expected } from '../../fixtures/post_render'; +type RenderPostFilterParams = Parameters; +type RenderPostFilterReturn = ReturnType; describe('Render post', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Post = hexo.model('Post'); const Page = hexo.model('Page'); - const renderPost = require('../../../dist/plugins/filter/before_generate/render_post').bind(hexo); + const renderPost: (...args: RenderPostFilterParams) => RenderPostFilterReturn = renderPostFilter.bind(hexo); before(async () => { await hexo.init(); diff --git a/test/scripts/filters/save_database.js b/test/scripts/filters/save_database.ts similarity index 59% rename from test/scripts/filters/save_database.js rename to test/scripts/filters/save_database.ts index f479cdc411..030b9151cb 100644 --- a/test/scripts/filters/save_database.js +++ b/test/scripts/filters/save_database.ts @@ -1,12 +1,14 @@ -'use strict'; - -const { exists, unlink } = require('hexo-fs'); -const Promise = require('bluebird'); +import Hexo from '../../../lib/hexo'; +import { exists, unlink } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import saveDatabaseFilter from '../../../lib/plugins/filter/before_exit/save_database'; +type SaveDatabaseFilterParams = Parameters +type SaveDatabaseFilterReturn = ReturnType describe('Save database', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const saveDatabase = Promise.method(require('../../../dist/plugins/filter/before_exit/save_database')).bind(hexo); + const saveDatabase: (...args: SaveDatabaseFilterParams) => Promise = Promise.method(saveDatabaseFilter).bind(hexo); const dbPath = hexo.database.options.path; it('default', async () => { diff --git a/test/scripts/filters/titlecase.js b/test/scripts/filters/titlecase.ts similarity index 72% rename from test/scripts/filters/titlecase.js rename to test/scripts/filters/titlecase.ts index 10b979c326..bd6a9ad695 100644 --- a/test/scripts/filters/titlecase.js +++ b/test/scripts/filters/titlecase.ts @@ -1,9 +1,11 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import titlecaseFilter from '../../../lib/plugins/filter/before_post_render/titlecase'; +type titlecaseFilterParams = Parameters; +type titlecaseFilterReturn = ReturnType; describe('Titlecase', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const titlecase = require('../../../dist/plugins/filter/before_post_render/titlecase').bind(hexo); + const titlecase: (...args: titlecaseFilterParams) => titlecaseFilterReturn = titlecaseFilter.bind(hexo); it('disabled', () => { const title = 'Today is a good day'; diff --git a/test/scripts/generators/asset.js b/test/scripts/generators/asset.ts similarity index 75% rename from test/scripts/generators/asset.js rename to test/scripts/generators/asset.ts index 3e898cc671..185de808f9 100644 --- a/test/scripts/generators/asset.js +++ b/test/scripts/generators/asset.ts @@ -1,18 +1,21 @@ -'use strict'; - -const { join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const testUtil = require('../../util'); -const { spy } = require('sinon'); +import { join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +import { readStream } from '../../util'; +import Hexo from '../../../lib/hexo'; +import assetGenerator from '../../../lib/plugins/generator/asset'; +import { spy } from 'sinon'; +import chai from 'chai'; +const should = chai.should(); +type AssetParams = Parameters +type AssetReturn = ReturnType describe('asset', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'asset_test'), {silent: true}); - const generator = require('../../../dist/plugins/generator/asset').bind(hexo); + const generator: (...args: AssetParams) => AssetReturn = assetGenerator.bind(hexo); const Asset = hexo.model('Asset'); const checkStream = async (stream, expected) => { - const data = await testUtil.stream.read(stream); + const data = await readStream(stream); data.should.eql(expected); }; @@ -32,11 +35,11 @@ describe('asset', () => { Asset.insert({_id: path, path}), writeFile(source, content) ]); - const data = await generator(hexo.locals); + const data = await generator(); data[0].path.should.eql('test.json'); data[0].data.modified.should.be.true; - const result = await data[0].data.data(); + const result = await data[0].data.data!(); result.should.eql('{"foo":"bar"}'); await Promise.all([ @@ -56,10 +59,10 @@ describe('asset', () => { Asset.insert({_id: path, path}), writeFile(source, content) ]); - const data = await generator(hexo.locals); + const data = await generator(); data[0].path.should.eql('test.json'); data[0].data.modified.should.be.true; - await data[0].data.data(); + await data[0].data.data!(); logSpy.called.should.be.true; logSpy.args[0][1].should.contains('Asset render failed: %s'); @@ -79,11 +82,11 @@ describe('asset', () => { Asset.insert({_id: path, path}), writeFile(source, content) ]); - const data = await generator(hexo.locals); + const data = await generator(); data[0].path.should.eql(path); data[0].data.modified.should.be.true; - await checkStream(data[0].data.data(), content); + await checkStream(data[0].data.data!(), content); await Promise.all([ Asset.removeById(path), @@ -100,11 +103,11 @@ describe('asset', () => { Asset.insert({_id: path, path, renderable: false}), writeFile(source, content) ]); - const data = await generator(hexo.locals); + const data = await generator(); data[0].path.should.eql('test.yml'); data[0].data.modified.should.be.true; - await checkStream(data[0].data.data(), content); + await checkStream(data[0].data.data!(), content); await Promise.all([ Asset.removeById(path), unlink(source) @@ -118,7 +121,7 @@ describe('asset', () => { _id: path, path }); - await generator(hexo.locals); + await generator(); should.not.exist(Asset.findById(path)); }); @@ -130,7 +133,7 @@ describe('asset', () => { Asset.insert({_id: path, path}), writeFile(source, '') ]); - const data = await generator(hexo.locals); + const data = await generator(); data[0].path.should.eql('test.min.js'); await Promise.all([ diff --git a/test/scripts/generators/index.js b/test/scripts/generators/index.js deleted file mode 100644 index 50de37dd14..0000000000 --- a/test/scripts/generators/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -describe('Generators', () => { - require('./asset'); - require('./page'); - require('./post'); -}); diff --git a/test/scripts/generators/page.js b/test/scripts/generators/page.ts similarity index 61% rename from test/scripts/generators/page.js rename to test/scripts/generators/page.ts index cf0290c640..40acb39c17 100644 --- a/test/scripts/generators/page.js +++ b/test/scripts/generators/page.ts @@ -1,14 +1,19 @@ -'use strict'; - -const Promise = require('bluebird'); +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import pageGenerator from '../../../lib/plugins/generator/page'; +import { NormalPostGenerator } from '../../../lib/types'; +import chai from 'chai'; +const should = chai.should(); +type PageGeneratorParams = Parameters; +type PageGeneratorReturn = ReturnType; describe('page', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname, {silent: true}); const Page = hexo.model('Page'); - const generator = Promise.method(require('../../../dist/plugins/generator/page').bind(hexo)); + const generator: (...args: PageGeneratorParams) => Promise = Promise.method(pageGenerator.bind(hexo)); - const locals = () => { + const locals = (): any => { hexo.locals.invalidate(); return hexo.locals.toObject(); }; @@ -38,7 +43,7 @@ describe('page', () => { path: 'bar', layout: 'photo' }); - const data = await generator(locals()); + const data = await generator(locals()) as NormalPostGenerator[]; data[0].layout.should.eql(['photo', 'page', 'post', 'index']); page.remove(); @@ -51,7 +56,7 @@ describe('page', () => { path: 'bar', layout }); - const data = await generator(locals()); + const data = await generator(locals()) as NormalPostGenerator[]; should.not.exist(data[0].layout); page.remove(); diff --git a/test/scripts/generators/post.js b/test/scripts/generators/post.ts similarity index 59% rename from test/scripts/generators/post.js rename to test/scripts/generators/post.ts index ace0d2e859..c99fb6922a 100644 --- a/test/scripts/generators/post.js +++ b/test/scripts/generators/post.ts @@ -1,19 +1,24 @@ -'use strict'; - -const Promise = require('bluebird'); +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import postGenerator from '../../../lib/plugins/generator/post'; +import { NormalPostGenerator } from '../../../lib/types'; +import chai from 'chai'; +const should = chai.should(); +type PostGeneratorParams = Parameters; +type PostGeneratorReturn = ReturnType; describe('post', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname, {silent: true}); const Post = hexo.model('Post'); - const generator = Promise.method(require('../../../dist/plugins/generator/post').bind(hexo)); + const generator: (...args: PostGeneratorParams) => Promise = Promise.method(postGenerator.bind(hexo)); hexo.config.permalink = ':title/'; - function locals() { + const locals = (): any => { hexo.locals.invalidate(); return hexo.locals.toObject(); - } + }; before(() => hexo.init()); @@ -42,7 +47,7 @@ describe('post', () => { slug: 'bar', layout: 'photo' }); - const data = await generator(locals()); + const data = await generator(locals()) as NormalPostGenerator[]; data[0].layout.should.eql(['photo', 'post', 'page', 'index']); post.remove(); @@ -54,7 +59,7 @@ describe('post', () => { slug: 'bar', layout: false }); - const data = await generator(locals()); + const data = await generator(locals()) as NormalPostGenerator[]; should.not.exist(data[0].layout); post.remove(); @@ -66,12 +71,12 @@ describe('post', () => { {source: 'bar', slug: 'bar', date: 1e8 + 1}, {source: 'baz', slug: 'baz', date: 1e8 - 1} ]); - const data = await generator(locals()); + const data = await generator(locals()) as NormalPostGenerator[]; should.not.exist(data[0].data.prev); - data[0].data.next._id.should.eq(posts[0]._id); - data[1].data.prev._id.should.eq(posts[1]._id); - data[1].data.next._id.should.eq(posts[2]._id); - data[2].data.prev._id.should.eq(posts[0]._id); + data[0].data.next!._id!.should.eq(posts[0]._id); + data[1].data.prev!._id!.should.eq(posts[1]._id); + data[1].data.next!._id!.should.eq(posts[2]._id); + data[2].data.prev!._id!.should.eq(posts[0]._id); should.not.exist(data[2].data.next); await Promise.all(posts.map(post => post.remove())); diff --git a/test/scripts/helpers/css.js b/test/scripts/helpers/css.ts similarity index 82% rename from test/scripts/helpers/css.js rename to test/scripts/helpers/css.ts index 6241ff93fd..b6a6794377 100644 --- a/test/scripts/helpers/css.js +++ b/test/scripts/helpers/css.ts @@ -1,16 +1,17 @@ -'use strict'; - -const cheerio = require('cheerio'); +import cheerio from 'cheerio'; +import Hexo from '../../../lib/hexo'; +import cssHelper from '../../../lib/plugins/helper/css'; +type CssHelperParams = Parameters; +type CssHelperReturn = ReturnType; describe('css', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const ctx = { + const ctx: any = { config: hexo.config }; - const css = require('../../../dist/plugins/helper/css').bind(ctx); + const css: (...args: CssHelperParams) => CssHelperReturn = cssHelper.bind(ctx); function assertResult(result, expected) { const $ = cheerio.load(result); @@ -21,10 +22,10 @@ describe('css', () => { expected.forEach((item, index) => { if (typeof item === 'string' || item instanceof String) { - $('link').eq(index).attr('href').should.eql(item); + $('link').eq(index).attr('href')!.should.eql(item); } else { for (const attribute in item) { - $('link').eq(index).attr(attribute).should.eql(item[attribute]); + $('link').eq(index).attr(attribute)!.should.eql(item[attribute]); } } }); @@ -62,7 +63,7 @@ describe('css', () => { assertResult(css({href: '/script.css', foo: 'bar'}), {href: '/script.css', foo: 'bar'}); }); - it('mulitple objects', () => { + it('multiple objects', () => { assertResult(css({href: '/foo.css'}, {href: '/bar.css'}), [{href: '/foo.css'}, {href: '/bar.css'}]); assertResult(css({href: '/aaa.css', bbb: 'ccc'}, {href: '/ddd.css', eee: 'fff'}), [{href: '/aaa.css', bbb: 'ccc'}, {href: '/ddd.css', eee: 'fff'}]); diff --git a/test/scripts/helpers/date.js b/test/scripts/helpers/date.ts similarity index 78% rename from test/scripts/helpers/date.js rename to test/scripts/helpers/date.ts index 80e5cfa510..f02e8fbaba 100644 --- a/test/scripts/helpers/date.js +++ b/test/scripts/helpers/date.ts @@ -1,12 +1,20 @@ -'use strict'; - -const moment = require('moment-timezone'); -const { useFakeTimers } = require('sinon'); +import moment from 'moment-timezone'; +import { useFakeTimers } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import { date as dateHelper, date_xml, relative_date, time as timeHelper, full_date, time_tag, toMomentLocale } from '../../../lib/plugins/helper/date'; +type DateHelperParams = Parameters; +type DateHelperReturn = ReturnType; +type TimeHelperParams = Parameters; +type TimeHelperReturn = ReturnType; +type FullDateHelperParams = Parameters; +type FullDateHelperReturn = ReturnType; +type TimeTagHelperParams = Parameters; +type TimeTagHelperReturn = ReturnType; +type RelativeDateHelperParams = Parameters; +type RelativeDateHelperReturn = ReturnType; describe('date', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const dateHelper = require('../../../dist/plugins/helper/date'); let clock; before(() => { @@ -18,12 +26,12 @@ describe('date', () => { }); it('date', () => { - const ctx = { + const ctx: any = { config: hexo.config, page: {} }; - const date = dateHelper.date.bind(ctx); + const date: (...args: DateHelperParams) => DateHelperReturn = dateHelper.bind(ctx); // now date().should.eql(moment().format(hexo.config.date_format)); @@ -57,7 +65,7 @@ describe('date', () => { }); it('date_xml', () => { - const dateXML = dateHelper.date_xml; + const dateXML = date_xml; // now dateXML().should.eql(moment().toISOString()); @@ -78,7 +86,7 @@ describe('date', () => { page: {} }; - const relativeDate = dateHelper.relative_date.bind(ctx); + const relativeDate: (...args: RelativeDateHelperParams) => RelativeDateHelperReturn = relative_date.bind(ctx); // now relativeDate().should.eql(moment().fromNow()); @@ -94,12 +102,12 @@ describe('date', () => { }); it('time', () => { - const ctx = { + const ctx: any = { config: hexo.config, page: {} }; - const time = dateHelper.time.bind(ctx); + const time: (...args: TimeHelperParams) => TimeHelperReturn = timeHelper.bind(ctx); // now time().should.eql(moment().format(hexo.config.time_format)); @@ -133,14 +141,14 @@ describe('date', () => { }); it('full_date', () => { - const ctx = { + const ctx: any = { config: hexo.config, - date: dateHelper.date, - time: dateHelper.time, + date: dateHelper, + time: timeHelper, page: {} }; - const fullDate = dateHelper.full_date.bind(ctx); + const fullDate: (...args: FullDateHelperParams) => FullDateHelperReturn = full_date.bind(ctx); const fullDateFormat = hexo.config.date_format + ' ' + hexo.config.time_format; // now @@ -175,21 +183,21 @@ describe('date', () => { }); it('time_tag', () => { - const ctx = { + const ctx: any = { config: hexo.config, - date: dateHelper.date, + date: dateHelper, page: {} }; - const timeTag = dateHelper.time_tag.bind(ctx); + const timeTag: (...args: TimeTagHelperParams) => TimeTagHelperReturn = time_tag.bind(ctx); - function result(date, format) { + function result(date?, format?) { date = date || new Date(); format = format || hexo.config.date_format; return ''; } - function check(date, format) { + function check(date, format?) { format = format || hexo.config.date_format; timeTag(date, format).should.eql(result(date, format)); } @@ -226,9 +234,8 @@ describe('date', () => { }); it('toMomentLocale', () => { - const toMomentLocale = dateHelper.toMomentLocale; - (toMomentLocale(undefined) === undefined).should.be.true; + // @ts-ignore toMomentLocale(null).should.eql('en'); toMomentLocale('').should.eql('en'); toMomentLocale('en').should.eql('en'); diff --git a/test/scripts/helpers/debug.js b/test/scripts/helpers/debug.ts similarity index 51% rename from test/scripts/helpers/debug.js rename to test/scripts/helpers/debug.ts index 200dc33705..c689565005 100644 --- a/test/scripts/helpers/debug.js +++ b/test/scripts/helpers/debug.ts @@ -1,33 +1,30 @@ -'use strict'; - -const { stub } = require('sinon'); +import { stub } from 'sinon'; +import { inspectObject, log } from '../../../lib/plugins/helper/debug'; +import { inspect } from 'util'; describe('debug', () => { - const debug = require('../../../dist/plugins/helper/debug'); - const { inspect } = require('util'); - it('inspect simple object', () => { const obj = { foo: 'bar' }; - debug.inspectObject(obj).should.eql(inspect(obj)); + inspectObject(obj).should.eql(inspect(obj)); }); it('inspect circular object', () => { - const obj = { foo: 'bar' }; + const obj: any = { foo: 'bar' }; obj.circular = obj; - debug.inspectObject(obj).should.eql(inspect(obj)); + inspectObject(obj).should.eql(inspect(obj)); }); it('inspect deep object', () => { const obj = { baz: { thud: 'narf', dur: { foo: 'bar', baz: { bang: 'zoom' } } } }; - debug.inspectObject(obj, {depth: 2}).should.not.eql(inspect(obj, {depth: 5})); - debug.inspectObject(obj, {depth: 5}).should.eql(inspect(obj, {depth: 5})); + inspectObject(obj, {depth: 2}).should.not.eql(inspect(obj, {depth: 5})); + inspectObject(obj, {depth: 5}).should.eql(inspect(obj, {depth: 5})); }); it('log should print to console', () => { const logStub = stub(console, 'log'); try { - debug.log('Hello %s from debug.log()!', 'World'); + log('Hello %s from debug.log()!', 'World'); } finally { logStub.restore(); } diff --git a/test/scripts/helpers/escape_html.js b/test/scripts/helpers/escape_html.ts similarity index 83% rename from test/scripts/helpers/escape_html.js rename to test/scripts/helpers/escape_html.ts index 802a85b8b8..ba801c6d2b 100644 --- a/test/scripts/helpers/escape_html.js +++ b/test/scripts/helpers/escape_html.ts @@ -1,8 +1,6 @@ -'use strict'; +import { escapeHTML } from '../../../lib/plugins/helper/format'; describe('escape_html', () => { - const { escapeHTML } = require('../../../dist/plugins/helper/format'); - it('default', () => { escapeHTML('

Hello "world".

').should.eql('<p class="foo">Hello "world".</p>'); }); diff --git a/test/scripts/helpers/favicon_tag.js b/test/scripts/helpers/favicon_tag.js deleted file mode 100644 index 2057042510..0000000000 --- a/test/scripts/helpers/favicon_tag.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -describe('favicon_tag', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(__dirname); - - const ctx = { - config: hexo.config - }; - - const favicon = require('../../../dist/plugins/helper/favicon_tag').bind(ctx); - - it('path', () => { - favicon('favicon.ico').should.eql(''); - }); -}); diff --git a/test/scripts/helpers/favicon_tag.ts b/test/scripts/helpers/favicon_tag.ts new file mode 100644 index 0000000000..b4139ba3c4 --- /dev/null +++ b/test/scripts/helpers/favicon_tag.ts @@ -0,0 +1,18 @@ +import Hexo from '../../../lib/hexo'; +import faviconTag from '../../../lib/plugins/helper/favicon_tag'; +type faviconTagParams = Parameters; +type faviconTagReturn = ReturnType; + +describe('favicon_tag', () => { + const hexo = new Hexo(__dirname); + + const ctx = { + config: hexo.config + }; + + const favicon: (...args: faviconTagParams) => faviconTagReturn = faviconTag.bind(ctx); + + it('path', () => { + favicon('favicon.ico').should.eql(''); + }); +}); diff --git a/test/scripts/helpers/feed_tag.js b/test/scripts/helpers/feed_tag.ts similarity index 86% rename from test/scripts/helpers/feed_tag.js rename to test/scripts/helpers/feed_tag.ts index 9dd96328f5..03961a50b9 100644 --- a/test/scripts/helpers/feed_tag.js +++ b/test/scripts/helpers/feed_tag.ts @@ -1,7 +1,11 @@ -'use strict'; +import feedTag from '../../../lib/plugins/helper/feed_tag'; +import chai from 'chai'; +const should = chai.should(); +type FeedTagParams = Parameters; +type FeedTagReturn = ReturnType; describe('feed_tag', () => { - const ctx = { + const ctx: any = { config: { title: 'Hexo', url: 'http://example.com', @@ -12,7 +16,7 @@ describe('feed_tag', () => { beforeEach(() => { ctx.config.feed = {}; }); - const feed = require('../../../dist/plugins/helper/feed_tag').bind(ctx); + const feed: (...args: FeedTagParams) => FeedTagReturn = feedTag.bind(ctx); it('path - atom', () => { feed('atom.xml').should.eql(''); @@ -35,16 +39,19 @@ describe('feed_tag', () => { }); it('invalid input - number', () => { + // @ts-ignore should.throw(() => feed(123), 'path must be a string!'); }); it('invalid input - undefined', () => { delete ctx.config.feed; + // @ts-ignore feed().should.eql(''); }); it('invalid input - empty', () => { ctx.config.feed = {}; + // @ts-ignore feed().should.eql(''); }); diff --git a/test/scripts/helpers/fragment_cache.js b/test/scripts/helpers/fragment_cache.ts similarity index 79% rename from test/scripts/helpers/fragment_cache.js rename to test/scripts/helpers/fragment_cache.ts index f9e391a492..814455e76d 100644 --- a/test/scripts/helpers/fragment_cache.js +++ b/test/scripts/helpers/fragment_cache.ts @@ -1,9 +1,9 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import fragmentCache from '../../../lib/plugins/helper/fragment_cache'; describe('fragment_cache', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const fragment_cache = require('../../../dist/plugins/helper/fragment_cache')(hexo); + const fragment_cache = fragmentCache(hexo); fragment_cache.call({cache: true}, 'foo', () => 123); diff --git a/test/scripts/helpers/full_url_for.js b/test/scripts/helpers/full_url_for.ts old mode 100755 new mode 100644 similarity index 70% rename from test/scripts/helpers/full_url_for.js rename to test/scripts/helpers/full_url_for.ts index 313de00273..334f734d13 --- a/test/scripts/helpers/full_url_for.js +++ b/test/scripts/helpers/full_url_for.ts @@ -1,11 +1,13 @@ -'use strict'; +import fullUrlForHelper from '../../../lib/plugins/helper/full_url_for'; +type FullUrlForHelperParams = Parameters; +type FullUrlForHelperReturn = ReturnType; describe('full_url_for', () => { - const ctx = { + const ctx: any = { config: { url: 'https://example.com' } }; - const fullUrlFor = require('../../../dist/plugins/helper/full_url_for').bind(ctx); + const fullUrlFor: (...args: FullUrlForHelperParams) => FullUrlForHelperReturn = fullUrlForHelper.bind(ctx); it('no path input', () => { fullUrlFor().should.eql(ctx.config.url + '/'); @@ -17,7 +19,7 @@ describe('full_url_for', () => { fullUrlFor('/index.html').should.eql(ctx.config.url + '/index.html'); }); - it('internel url (pretty_urls.trailing_index disabled)', () => { + it('internal url (pretty_urls.trailing_index disabled)', () => { ctx.config.pretty_urls = { trailing_index: false }; fullUrlFor('index.html').should.eql(ctx.config.url + '/'); fullUrlFor('/index.html').should.eql(ctx.config.url + '/'); diff --git a/test/scripts/helpers/gravatar.js b/test/scripts/helpers/gravatar.ts similarity index 80% rename from test/scripts/helpers/gravatar.js rename to test/scripts/helpers/gravatar.ts index 7fd79bfdba..e632026bf0 100644 --- a/test/scripts/helpers/gravatar.js +++ b/test/scripts/helpers/gravatar.ts @@ -1,14 +1,13 @@ -'use strict'; - -const crypto = require('crypto'); +import crypto from 'crypto'; +import gravatarHelper from '../../../lib/plugins/helper/gravatar'; describe('gravatar', () => { - const gravatar = require('../../../dist/plugins/helper/gravatar'); - function md5(str) { return crypto.createHash('md5').update(str).digest('hex'); } + const gravatar = gravatarHelper as any; + const email = 'abc@abc.com'; const hash = md5(email); diff --git a/test/scripts/helpers/image_tag.js b/test/scripts/helpers/image_tag.ts similarity index 70% rename from test/scripts/helpers/image_tag.js rename to test/scripts/helpers/image_tag.ts index f8a87edbbe..3b2e82691a 100644 --- a/test/scripts/helpers/image_tag.js +++ b/test/scripts/helpers/image_tag.ts @@ -1,14 +1,16 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import imageTag from '../../../lib/plugins/helper/image_tag'; +type imageTagParams = Parameters; +type imageTagReturn = ReturnType; describe('image_tag', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const ctx = { + const ctx: any = { config: hexo.config }; - const img = require('../../../dist/plugins/helper/image_tag').bind(ctx); + const img: (...args: imageTagParams) => imageTagReturn = imageTag.bind(ctx); it('path', () => { img('https://hexo.io/image.jpg').should.eql(''); diff --git a/test/scripts/helpers/index.js b/test/scripts/helpers/index.js deleted file mode 100644 index 068e6b040e..0000000000 --- a/test/scripts/helpers/index.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -describe('Helpers', () => { - require('./debug'); - require('./css'); - require('./date'); - require('./escape_html'); - require('./favicon_tag'); - require('./feed_tag'); - require('./fragment_cache'); - require('./full_url_for'); - require('./gravatar'); - require('./image_tag'); - require('./is'); - require('./js'); - require('./link_to'); - require('./list_archives'); - require('./list_categories'); - require('./list_posts'); - require('./list_tags'); - require('./mail_to'); - require('./markdown'); - require('./meta_generator'); - require('./number_format'); - require('./open_graph'); - require('./paginator'); - require('./partial'); - require('./relative_url'); - require('./render'); - require('./search_form'); - require('./tagcloud'); - require('./toc'); - require('./url_for'); -}); diff --git a/test/scripts/helpers/is.js b/test/scripts/helpers/is.js deleted file mode 100644 index cec0990aa9..0000000000 --- a/test/scripts/helpers/is.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -describe('is', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(__dirname); - const is = require('../../../dist/plugins/helper/is'); - - it('is_current', async () => { - await is.current.call({path: 'index.html', config: hexo.config}).should.be.true; - await is.current.call({path: 'tags/index.html', config: hexo.config}).should.be.false; - await is.current.call({path: 'index.html', config: hexo.config}, '/').should.be.true; - await is.current.call({path: 'index.html', config: hexo.config}, 'index.html').should.be.true; - await is.current.call({path: 'tags/index.html', config: hexo.config}, '/').should.be.false; - await is.current.call({path: 'tags/index.html', config: hexo.config}, '/index.html').should.be.false; - await is.current.call({path: 'index.html', config: hexo.config}, '/', true).should.be.true; - await is.current.call({path: 'index.html', config: hexo.config}, '/index.html', true).should.be.true; - await is.current.call({path: 'foo/bar', config: hexo.config}, 'foo', true).should.be.false; - await is.current.call({path: 'foo/bar', config: hexo.config}, 'foo').should.be.true; - await is.current.call({path: 'foo/bar', config: hexo.config}, 'foo/bar').should.be.true; - await is.current.call({path: 'foo/bar', config: hexo.config}, 'foo/baz').should.be.false; - }); - - it('is_home', async () => { - await is.home.call({page: {__index: true}}).should.be.true; - await is.home.call({page: {}}).should.be.false; - }); - - it('is_home_first_page', async () => { - await is.home_first_page.call({page: {__index: true, current: 1}}).should.be.true; - await is.home_first_page.call({page: {__index: true, current: 2}}).should.be.false; - await is.home_first_page.call({page: {__index: true}}).should.be.false; - await is.home_first_page.call({page: {}}).should.be.false; - }); - - it('is_post', async () => { - await is.post.call({page: {__post: true}}).should.be.true; - await is.post.call({page: {}}).should.be.false; - }); - - it('is_page', async () => { - await is.page.call({page: {__page: true}}).should.be.true; - await is.page.call({page: {}}).should.be.false; - }); - - it('is_archive', async () => { - await is.archive.call({page: {}}).should.be.false; - await is.archive.call({page: {archive: true}}).should.be.true; - await is.archive.call({page: {archive: false}}).should.be.false; - }); - - it('is_year', async () => { - await is.year.call({page: {}}).should.be.false; - await is.year.call({page: {archive: true}}).should.be.false; - await is.year.call({page: {archive: true, year: 2014}}).should.be.true; - await is.year.call({page: {archive: true, year: 2014}}, 2014).should.be.true; - await is.year.call({page: {archive: true, year: 2014}}, 2015).should.be.false; - await is.year.call({page: {archive: true, year: 2014, month: 10}}).should.be.true; - }); - - it('is_month', async () => { - await is.month.call({page: {}}).should.be.false; - await is.month.call({page: {archive: true}}).should.be.false; - await is.month.call({page: {archive: true, year: 2014}}).should.be.false; - await is.month.call({page: {archive: true, year: 2014, month: 10}}).should.be.true; - await is.month.call({page: {archive: true, year: 2014, month: 10}}, 2014, 10).should.be.true; - await is.month.call({page: {archive: true, year: 2014, month: 10}}, 2015, 10).should.be.false; - await is.month.call({page: {archive: true, year: 2014, month: 10}}, 2014, 12).should.be.false; - await is.month.call({page: {archive: true, year: 2014, month: 10}}, 10).should.be.true; - await is.month.call({page: {archive: true, year: 2014, month: 10}}, 12).should.be.false; - }); - - it('is_category', async () => { - await is.category.call({page: {category: 'foo'}}).should.be.true; - await is.category.call({page: {category: 'foo'}}, 'foo').should.be.true; - await is.category.call({page: {category: 'foo'}}, 'bar').should.be.false; - await is.category.call({page: {}}).should.be.false; - }); - - it('is_tag', async () => { - await is.tag.call({page: {tag: 'foo'}}).should.be.true; - await is.tag.call({page: {tag: 'foo'}}, 'foo').should.be.true; - await is.tag.call({page: {tag: 'foo'}}, 'bar').should.be.false; - await is.tag.call({page: {}}).should.be.false; - }); -}); diff --git a/test/scripts/helpers/is.ts b/test/scripts/helpers/is.ts new file mode 100644 index 0000000000..66ae81d27a --- /dev/null +++ b/test/scripts/helpers/is.ts @@ -0,0 +1,84 @@ +import Hexo from '../../../lib/hexo'; +import { current, home, home_first_page, post, page, archive, year, month, category, tag } from '../../../lib/plugins/helper/is'; + +describe('is', () => { + const hexo = new Hexo(__dirname); + + it('is_current', async () => { + await current.call({path: 'index.html', config: hexo.config}).should.be.true; + await current.call({path: 'tags/index.html', config: hexo.config}).should.be.false; + await current.call({path: 'index.html', config: hexo.config}, '/').should.be.true; + await current.call({path: 'index.html', config: hexo.config}, 'index.html').should.be.true; + await current.call({path: 'tags/index.html', config: hexo.config}, '/').should.be.false; + await current.call({path: 'tags/index.html', config: hexo.config}, '/index.html').should.be.false; + await current.call({path: 'index.html', config: hexo.config}, '/', true).should.be.true; + await current.call({path: 'index.html', config: hexo.config}, '/index.html', true).should.be.true; + await current.call({path: 'foo/bar', config: hexo.config}, 'foo', true).should.be.false; + await current.call({path: 'foo/bar', config: hexo.config}, 'foo').should.be.true; + await current.call({path: 'foo/bar', config: hexo.config}, 'foo/bar').should.be.true; + await current.call({path: 'foo/bar', config: hexo.config}, 'foo/baz').should.be.false; + }); + + it('is_home', async () => { + await home.call({page: {__index: true}}).should.be.true; + await home.call({page: {}}).should.be.false; + }); + + it('is_home_first_page', async () => { + await home_first_page.call({page: {__index: true, current: 1}}).should.be.true; + await home_first_page.call({page: {__index: true, current: 2}}).should.be.false; + await home_first_page.call({page: {__index: true}}).should.be.false; + await home_first_page.call({page: {}}).should.be.false; + }); + + it('is_post', async () => { + await post.call({page: {__post: true}}).should.be.true; + await post.call({page: {}}).should.be.false; + }); + + it('is_page', async () => { + await page.call({page: {__page: true}}).should.be.true; + await page.call({page: {}}).should.be.false; + }); + + it('is_archive', async () => { + await archive.call({page: {}}).should.be.false; + await archive.call({page: {archive: true}}).should.be.true; + await archive.call({page: {archive: false}}).should.be.false; + }); + + it('is_year', async () => { + await year.call({page: {}}).should.be.false; + await year.call({page: {archive: true}}).should.be.false; + await year.call({page: {archive: true, year: 2014}}).should.be.true; + await year.call({page: {archive: true, year: 2014}}, 2014).should.be.true; + await year.call({page: {archive: true, year: 2014}}, 2015).should.be.false; + await year.call({page: {archive: true, year: 2014, month: 10}}).should.be.true; + }); + + it('is_month', async () => { + await month.call({page: {}}).should.be.false; + await month.call({page: {archive: true}}).should.be.false; + await month.call({page: {archive: true, year: 2014}}).should.be.false; + await month.call({page: {archive: true, year: 2014, month: 10}}).should.be.true; + await month.call({page: {archive: true, year: 2014, month: 10}}, 2014, 10).should.be.true; + await month.call({page: {archive: true, year: 2014, month: 10}}, 2015, 10).should.be.false; + await month.call({page: {archive: true, year: 2014, month: 10}}, 2014, 12).should.be.false; + await month.call({page: {archive: true, year: 2014, month: 10}}, 10).should.be.true; + await month.call({page: {archive: true, year: 2014, month: 10}}, 12).should.be.false; + }); + + it('is_category', async () => { + await category.call({page: {category: 'foo'}}).should.be.true; + await category.call({page: {category: 'foo'}}, 'foo').should.be.true; + await category.call({page: {category: 'foo'}}, 'bar').should.be.false; + await category.call({page: {}}).should.be.false; + }); + + it('is_tag', async () => { + await tag.call({page: {tag: 'foo'}}).should.be.true; + await tag.call({page: {tag: 'foo'}}, 'foo').should.be.true; + await tag.call({page: {tag: 'foo'}}, 'bar').should.be.false; + await tag.call({page: {}}).should.be.false; + }); +}); diff --git a/test/scripts/helpers/js.js b/test/scripts/helpers/js.ts similarity index 82% rename from test/scripts/helpers/js.js rename to test/scripts/helpers/js.ts index 22a23805b1..00d8f40e4d 100644 --- a/test/scripts/helpers/js.js +++ b/test/scripts/helpers/js.ts @@ -1,16 +1,17 @@ -'use strict'; - -const cheerio = require('cheerio'); +import cheerio from 'cheerio'; +import Hexo from '../../../lib/hexo'; +import jsHelper from '../../../lib/plugins/helper/js'; +type JsHelperParams = Parameters; +type JsHelperReturn = ReturnType; describe('js', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const ctx = { + const ctx: any = { config: hexo.config }; - const js = require('../../../dist/plugins/helper/js').bind(ctx); + const js: (...args: JsHelperParams) => JsHelperReturn = jsHelper.bind(ctx); function assertResult(result, expected) { const $ = cheerio.load(result); @@ -21,13 +22,13 @@ describe('js', () => { expected.forEach((item, index) => { if (typeof item === 'string' || item instanceof String) { - $('script').eq(index).attr('src').should.eql(item); + $('script').eq(index).attr('src')!.should.eql(item); } else { for (const attribute in item) { if (item[attribute] === true) { - $('script').eq(index).attr(attribute).should.eql(attribute); + $('script').eq(index).attr(attribute)!.should.eql(attribute); } else { - $('script').eq(index).attr(attribute).should.eql(item[attribute]); + $('script').eq(index).attr(attribute)!.should.eql(item[attribute]); } } } @@ -66,7 +67,7 @@ describe('js', () => { assertResult(js({src: '/script.js', foo: 'bar'}), {src: '/script.js', foo: 'bar'}); }); - it('mulitple objects', () => { + it('multiple objects', () => { assertResult(js({src: '/foo.js'}, {src: '/bar.js'}), [{src: '/foo.js'}, {src: '/bar.js'}]); assertResult(js({src: '/aaa.js', bbb: 'ccc'}, {src: '/ddd.js', eee: 'fff'}), [{src: '/aaa.js', bbb: 'ccc'}, {src: '/ddd.js', eee: 'fff'}]); diff --git a/test/scripts/helpers/link_to.js b/test/scripts/helpers/link_to.ts similarity index 79% rename from test/scripts/helpers/link_to.js rename to test/scripts/helpers/link_to.ts index 528a0ce7b8..3bc24891c4 100644 --- a/test/scripts/helpers/link_to.js +++ b/test/scripts/helpers/link_to.ts @@ -1,14 +1,16 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import linkToHelper from '../../../lib/plugins/helper/link_to'; +type LinkToHelperParams = Parameters; +type LinkToHelperReturn = ReturnType; describe('link_to', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const ctx = { + const ctx: any = { config: hexo.config }; - const linkTo = require('../../../dist/plugins/helper/link_to').bind(ctx); + const linkTo: (...args: LinkToHelperParams) => LinkToHelperReturn = linkToHelper.bind(ctx); it('path', () => { linkTo('https://hexo.io/').should.eql('hexo.io'); diff --git a/test/scripts/helpers/list_archives.js b/test/scripts/helpers/list_archives.ts similarity index 95% rename from test/scripts/helpers/list_archives.js rename to test/scripts/helpers/list_archives.ts index b733a60c6c..43ea874267 100644 --- a/test/scripts/helpers/list_archives.js +++ b/test/scripts/helpers/list_archives.ts @@ -1,16 +1,18 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import listArchivesHelper from '../../../lib/plugins/helper/list_archives'; +type ListArchivesHelperParams = Parameters; +type ListArchivesHelperReturn = ReturnType; describe('list_archives', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); - const ctx = { + const ctx: any = { config: hexo.config, page: {} }; - const listArchives = require('../../../dist/plugins/helper/list_archives').bind(ctx); + const listArchives: (...args: ListArchivesHelperParams) => ListArchivesHelperReturn = listArchivesHelper.bind(ctx); function resetLocals() { hexo.locals.invalidate(); diff --git a/test/scripts/helpers/list_categories.js b/test/scripts/helpers/list_categories.ts similarity index 96% rename from test/scripts/helpers/list_categories.js rename to test/scripts/helpers/list_categories.ts index 5cdb46e01f..eccb59df7c 100644 --- a/test/scripts/helpers/list_categories.js +++ b/test/scripts/helpers/list_categories.ts @@ -1,16 +1,18 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import listCategoriesHelper from '../../../lib/plugins/helper/list_categories'; +type ListCategoriesHelperParams = Parameters; +type ListCategoriesHelperReturn = ReturnType; describe('list_categories', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); const Category = hexo.model('Category'); - const ctx = { + const ctx: any = { config: hexo.config }; - const listCategories = require('../../../dist/plugins/helper/list_categories').bind(ctx); + const listCategories: (...args: ListCategoriesHelperParams) => ListCategoriesHelperReturn = listCategoriesHelper.bind(ctx); before(async () => { await hexo.init(); diff --git a/test/scripts/helpers/list_posts.js b/test/scripts/helpers/list_posts.ts similarity index 91% rename from test/scripts/helpers/list_posts.js rename to test/scripts/helpers/list_posts.ts index dbb6810331..7c6a14c2d8 100644 --- a/test/scripts/helpers/list_posts.js +++ b/test/scripts/helpers/list_posts.ts @@ -1,15 +1,17 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import listPostsHelper from '../../../lib/plugins/helper/list_posts'; +type ListPostsHelperParams = Parameters; +type ListPostsHelperReturn = ReturnType; describe('list_posts', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); - const ctx = { + const ctx: any = { config: hexo.config }; - const listPosts = require('../../../dist/plugins/helper/list_posts').bind(ctx); + const listPosts: (...args: ListPostsHelperParams) => ListPostsHelperReturn = listPostsHelper.bind(ctx); hexo.config.permalink = ':title/'; diff --git a/test/scripts/helpers/list_tags.js b/test/scripts/helpers/list_tags.ts similarity index 94% rename from test/scripts/helpers/list_tags.js rename to test/scripts/helpers/list_tags.ts index c5e196cc91..138c70d308 100644 --- a/test/scripts/helpers/list_tags.js +++ b/test/scripts/helpers/list_tags.ts @@ -1,16 +1,18 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import listTagsHelper from '../../../lib/plugins/helper/list_tags'; +type ListTagsHelperParams = Parameters; +type ListTagsHelperReturn = ReturnType; describe('list_tags', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); const Tag = hexo.model('Tag'); - const ctx = { + const ctx: any = { config: hexo.config }; - const listTags = require('../../../dist/plugins/helper/list_tags').bind(ctx); + const listTags: (...args: ListTagsHelperParams) => ListTagsHelperReturn = listTagsHelper.bind(ctx); before(async () => { await hexo.init(); @@ -207,15 +209,14 @@ describe('list_tags', () => { }); describe('list_tags transform', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); - const ctx = { + const ctx: any = { config: hexo.config }; - const listTags = require('../../../dist/plugins/helper/list_tags').bind(ctx); + const listTags: (...args: ListTagsHelperParams) => ListTagsHelperReturn = listTagsHelper.bind(ctx); before(async () => { await hexo.init(); diff --git a/test/scripts/helpers/mail_to.js b/test/scripts/helpers/mail_to.ts similarity index 89% rename from test/scripts/helpers/mail_to.js rename to test/scripts/helpers/mail_to.ts index 8dc09ded62..30e77952b4 100644 --- a/test/scripts/helpers/mail_to.js +++ b/test/scripts/helpers/mail_to.ts @@ -1,14 +1,16 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import mailToHelper from '../../../lib/plugins/helper/mail_to'; +type MailToHelperParams = Parameters; +type MailToHelperReturn = ReturnType; describe('mail_to', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const ctx = { + const ctx: any = { config: hexo.config }; - const mailto = require('../../../dist/plugins/helper/mail_to').bind(ctx); + const mailto: (...args: MailToHelperParams) => MailToHelperReturn = mailToHelper.bind(ctx); it('path', () => { mailto('abc@example.com').should.eql('abc@example.com'); diff --git a/test/scripts/helpers/markdown.js b/test/scripts/helpers/markdown.js deleted file mode 100644 index 5fd2cd6c38..0000000000 --- a/test/scripts/helpers/markdown.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -describe('markdown', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(__dirname); - - const ctx = { - render: require('../../../dist/plugins/helper/render')(hexo) - }; - - const markdown = require('../../../dist/plugins/helper/markdown').bind(ctx); - - before(() => hexo.init().then(() => hexo.loadPlugin(require.resolve('hexo-renderer-marked')))); - - it('default', () => { - markdown('123456 **bold** and *italic*').should.eql('

123456 bold and italic

\n'); - }); -}); diff --git a/test/scripts/helpers/markdown.ts b/test/scripts/helpers/markdown.ts new file mode 100644 index 0000000000..3bcf3e4907 --- /dev/null +++ b/test/scripts/helpers/markdown.ts @@ -0,0 +1,21 @@ +import Hexo from '../../../lib/hexo'; +import renderHelper from '../../../lib/plugins/helper/render'; +import markdownHelper from '../../../lib/plugins/helper/markdown'; +type MarkdownHelperParams = Parameters; +type MarkdownHelperReturn = ReturnType; + +describe('markdown', () => { + const hexo = new Hexo(__dirname); + + const ctx = { + render: renderHelper(hexo) + }; + + const markdown: (...args: MarkdownHelperParams) => MarkdownHelperReturn = markdownHelper.bind(ctx); + + before(() => hexo.init().then(() => hexo.loadPlugin(require.resolve('hexo-renderer-marked')))); + + it('default', () => { + markdown('123456 **bold** and *italic*').should.eql('

123456 bold and italic

\n'); + }); +}); diff --git a/test/scripts/helpers/meta_generator.js b/test/scripts/helpers/meta_generator.js deleted file mode 100755 index 972820453e..0000000000 --- a/test/scripts/helpers/meta_generator.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -describe('meta_generator', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(); - - const metaGeneratorHelper = require('../../../dist/plugins/helper/meta_generator').bind(hexo); - - it('default', () => { - const { version } = hexo; - - should.exist(version); - metaGeneratorHelper().should.eql(``); - }); -}); diff --git a/test/scripts/helpers/meta_generator.ts b/test/scripts/helpers/meta_generator.ts new file mode 100644 index 0000000000..a3f5f8fc4a --- /dev/null +++ b/test/scripts/helpers/meta_generator.ts @@ -0,0 +1,19 @@ +import Hexo from '../../../lib/hexo'; +import metaGeneratorHelper from '../../../lib/plugins/helper/meta_generator'; +import chai from 'chai'; +const should = chai.should(); +type MetaGeneratorHelperParams = Parameters; +type MetaGeneratorHelperReturn = ReturnType; + +describe('meta_generator', () => { + const hexo = new Hexo(); + + const metaGenerator: (...args: MetaGeneratorHelperParams) => MetaGeneratorHelperReturn = metaGeneratorHelper.bind(hexo); + + it('default', () => { + const { version } = hexo; + + should.exist(version); + metaGenerator().should.eql(``); + }); +}); diff --git a/test/scripts/helpers/number_format.js b/test/scripts/helpers/number_format.ts similarity index 90% rename from test/scripts/helpers/number_format.js rename to test/scripts/helpers/number_format.ts index 32390637a5..a81c50fc2d 100644 --- a/test/scripts/helpers/number_format.js +++ b/test/scripts/helpers/number_format.ts @@ -1,8 +1,6 @@ -'use strict'; +import numberFormat from '../../../lib/plugins/helper/number_format'; describe('number_format', () => { - const numberFormat = require('../../../dist/plugins/helper/number_format'); - it('default', () => { numberFormat(1234.567).should.eql('1,234.567'); }); diff --git a/test/scripts/helpers/open_graph.js b/test/scripts/helpers/open_graph.ts similarity index 96% rename from test/scripts/helpers/open_graph.js rename to test/scripts/helpers/open_graph.ts index 433cddbe24..c8dd497ed8 100644 --- a/test/scripts/helpers/open_graph.js +++ b/test/scripts/helpers/open_graph.ts @@ -1,16 +1,13 @@ -'use strict'; - -const moment = require('moment'); -const cheerio = require('cheerio'); -const { encodeURL } = require('hexo-util'); -const defaultConfig = require('../../../dist/hexo/default_config'); +import moment from 'moment'; +import cheerio from 'cheerio'; +import { encodeURL, htmlTag as tag } from 'hexo-util'; +import defaultConfig from '../../../lib/hexo/default_config'; +import Hexo from '../../../lib/hexo'; +import openGraph from '../../../lib/plugins/helper/open_graph'; +import { post as isPost } from '../../../lib/plugins/helper/is'; describe('open_graph', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const openGraph = require('../../../dist/plugins/helper/open_graph'); - const isPost = require('../../../dist/plugins/helper/is').post; - const tag = require('hexo-util').htmlTag; const Post = hexo.model('Post'); function meta(options) { @@ -140,7 +137,7 @@ describe('open_graph', () => { const $ = cheerio.load(result); - $('meta[property="og:url"]').attr('content').endsWith('index.html').should.be.false; + $('meta[property="og:url"]').attr('content')!.endsWith('index.html').should.be.false; hexo.config.pretty_urls.trailing_index = true; }); @@ -156,13 +153,13 @@ describe('open_graph', () => { const $ = cheerio.load(result); - $('meta[property="og:url"]').attr('content').endsWith('.html').should.be.false; + $('meta[property="og:url"]').attr('content')!.endsWith('.html').should.be.false; hexo.config.pretty_urls.trailing_html = true; }); it('url - null pretty_urls', () => { - hexo.config.pretty_urls = null; + hexo.config.pretty_urls = null as any; const url = 'http://example.com/page/about.html'; const result = openGraph.call({ page: {}, @@ -173,7 +170,7 @@ describe('open_graph', () => { const $ = cheerio.load(result); - $('meta[property="og:url"]').attr('content').should.eql(url); + $('meta[property="og:url"]').attr('content')!.should.eql(url); hexo.config.pretty_urls = { trailing_index: true, diff --git a/test/scripts/helpers/paginator.js b/test/scripts/helpers/paginator.ts similarity index 95% rename from test/scripts/helpers/paginator.js rename to test/scripts/helpers/paginator.ts index fe46d685c8..2198aad73f 100644 --- a/test/scripts/helpers/paginator.js +++ b/test/scripts/helpers/paginator.ts @@ -1,12 +1,13 @@ -'use strict'; - -const { url_for } = require('hexo-util'); +import { url_for } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import paginatorHelper from '../../../lib/plugins/helper/paginator'; +type PaginatorHelperParams = Parameters; +type PaginatorHelperReturn = ReturnType; describe('paginator', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const ctx = { + const ctx: any = { page: { base: '', total: 10 @@ -15,7 +16,7 @@ describe('paginator', () => { config: hexo.config }; - const paginator = require('../../../dist/plugins/helper/paginator').bind(ctx); + const paginator: (...args: PaginatorHelperParams) => PaginatorHelperReturn = paginatorHelper.bind(ctx); function link(i) { return url_for.call(ctx, i === 1 ? '' : 'page/' + i + '/'); diff --git a/test/scripts/helpers/partial.js b/test/scripts/helpers/partial.ts similarity index 70% rename from test/scripts/helpers/partial.js rename to test/scripts/helpers/partial.ts index ca4b2133d4..85e7dbe35f 100644 --- a/test/scripts/helpers/partial.js +++ b/test/scripts/helpers/partial.ts @@ -1,17 +1,22 @@ -'use strict'; - -const pathFn = require('path'); -const fs = require('hexo-fs'); -const Promise = require('bluebird'); +import pathFn from 'path'; +import { mkdirs, writeFile, rmdir } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import fragmentCache from '../../../lib/plugins/helper/fragment_cache'; +import partialHelper from '../../../lib/plugins/helper/partial'; +import chai from 'chai'; +const should = chai.should(); +type PartialHelperParams = Parameters>; +type PartialHelperReturn = ReturnType>; describe('partial', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(pathFn.join(__dirname, 'partial_test'), {silent: true}); const themeDir = pathFn.join(hexo.base_dir, 'themes', 'test'); const viewDir = pathFn.join(themeDir, 'layout') + pathFn.sep; const viewName = 'article.njk'; - const ctx = { + const ctx: any = { site: hexo.locals, config: hexo.config, view_dir: viewDir, @@ -20,22 +25,22 @@ describe('partial', () => { cache: true }; - ctx.fragment_cache = require('../../../dist/plugins/helper/fragment_cache')(hexo); + ctx.fragment_cache = fragmentCache(hexo); hexo.env.init = true; - const partial = require('../../../dist/plugins/helper/partial')(hexo).bind(ctx); + const partial: (...args: PartialHelperParams) => PartialHelperReturn = partialHelper(hexo).bind(ctx); before(async () => { await Promise.all([ - fs.mkdirs(themeDir), - fs.writeFile(hexo.config_path, 'theme: test') + mkdirs(themeDir), + writeFile(hexo.config_path, 'theme: test') ]); await hexo.init(); hexo.theme.setView('widget/tag.njk', 'tag widget'); }); - after(() => fs.rmdir(hexo.base_dir)); + after(() => rmdir(hexo.base_dir)); it('default', () => { // relative path @@ -82,6 +87,7 @@ describe('partial', () => { }); it('name must be a string', () => { + // @ts-ignore should.throw(() => partial(), 'name must be a string!'); }); }); diff --git a/test/scripts/helpers/relative_url.js b/test/scripts/helpers/relative_url.ts similarity index 93% rename from test/scripts/helpers/relative_url.js rename to test/scripts/helpers/relative_url.ts index f9f691f602..215355f660 100644 --- a/test/scripts/helpers/relative_url.js +++ b/test/scripts/helpers/relative_url.ts @@ -1,8 +1,6 @@ -'use strict'; +import relativeURL from '../../../lib/plugins/helper/relative_url'; describe('relative_url', () => { - const relativeURL = require('../../../dist/plugins/helper/relative_url'); - it('from root', () => { relativeURL('', 'css/style.css').should.eql('css/style.css'); relativeURL('index.html', 'css/style.css').should.eql('css/style.css'); diff --git a/test/scripts/helpers/render.js b/test/scripts/helpers/render.ts similarity index 71% rename from test/scripts/helpers/render.js rename to test/scripts/helpers/render.ts index 04b8c9cc62..2d4061a5a5 100644 --- a/test/scripts/helpers/render.js +++ b/test/scripts/helpers/render.ts @@ -1,9 +1,9 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import renderHelper from '../../../lib/plugins/helper/render'; describe('render', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const render = require('../../../dist/plugins/helper/render')(hexo); + const render = renderHelper(hexo); before(() => hexo.init()); diff --git a/test/scripts/helpers/search_form.js b/test/scripts/helpers/search_form.ts similarity index 89% rename from test/scripts/helpers/search_form.js rename to test/scripts/helpers/search_form.ts index 6f086008e4..7de9cbaecc 100644 --- a/test/scripts/helpers/search_form.js +++ b/test/scripts/helpers/search_form.ts @@ -1,7 +1,9 @@ -'use strict'; +import searchFormHelper from '../../../lib/plugins/helper/search_form'; +type SearchFormHelperParams = Parameters; +type SearchFormHelperReturn = ReturnType; describe('search_form', () => { - const searchForm = require('../../../dist/plugins/helper/search_form').bind({ + const searchForm: (...args: SearchFormHelperParams) => SearchFormHelperReturn = searchFormHelper.bind({ config: {url: 'https://hexo.io'} }); @@ -50,6 +52,7 @@ describe('search_form', () => { }); it('button - ignore incorrect type', () => { + // @ts-ignore searchForm({button: {}, text: 'Find'}).should.eql('
' + '' + '' diff --git a/test/scripts/helpers/tagcloud.js b/test/scripts/helpers/tagcloud.ts similarity index 94% rename from test/scripts/helpers/tagcloud.js rename to test/scripts/helpers/tagcloud.ts index 47ffe87e51..3704694ee7 100644 --- a/test/scripts/helpers/tagcloud.js +++ b/test/scripts/helpers/tagcloud.ts @@ -1,18 +1,22 @@ -'use strict'; - -const Promise = require('bluebird'); +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import tagcloudHelper from '../../../lib/plugins/helper/tagcloud'; +import chai from 'chai'; +const should = chai.should(); +type TagcloudHelperParams = Parameters; +type TagcloudHelperReturn = ReturnType; describe('tagcloud', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const Post = hexo.model('Post'); const Tag = hexo.model('Tag'); - const ctx = { + const ctx: any = { config: hexo.config }; - const tagcloud = require('../../../dist/plugins/helper/tagcloud').bind(ctx); + const tagcloud: (...args: TagcloudHelperParams) => TagcloudHelperReturn = tagcloudHelper.bind(ctx); before(async () => { await hexo.init(); @@ -49,8 +53,9 @@ describe('tagcloud', () => { const hexo = new Hexo(__dirname); await hexo.init(); hexo.locals.invalidate(); + // @ts-ignore hexo.site = hexo.locals.toObject(); - const tagcloud = require('../../../dist/plugins/helper/tagcloud').bind(hexo); + const tagcloud: (...args: TagcloudHelperParams) => TagcloudHelperReturn = tagcloudHelper.bind(hexo); const result = tagcloud(); diff --git a/test/scripts/helpers/toc.js b/test/scripts/helpers/toc.ts similarity index 99% rename from test/scripts/helpers/toc.js rename to test/scripts/helpers/toc.ts index b93d7e1d6d..75b479b2ec 100644 --- a/test/scripts/helpers/toc.js +++ b/test/scripts/helpers/toc.ts @@ -1,10 +1,7 @@ -'use strict'; - -const { encodeURL, escapeHTML } = require('hexo-util'); +import { encodeURL, escapeHTML } from 'hexo-util'; +import toc from '../../../lib/plugins/helper/toc'; describe('toc', () => { - const toc = require('../../../dist/plugins/helper/toc'); - const html = [ '

Title 1

', '

Title 1.1

', diff --git a/test/scripts/helpers/url_for.js b/test/scripts/helpers/url_for.ts similarity index 80% rename from test/scripts/helpers/url_for.js rename to test/scripts/helpers/url_for.ts index 8f953a7d10..2c3c1d59e4 100644 --- a/test/scripts/helpers/url_for.js +++ b/test/scripts/helpers/url_for.ts @@ -1,12 +1,15 @@ -'use strict'; +import urlForHelper from '../../../lib/plugins/helper/url_for'; +import relativeUrlHelper from '../../../lib/plugins/helper/relative_url'; +type UrlForHelperParams = Parameters; +type UrlForHelperReturn = ReturnType; describe('url_for', () => { - const ctx = { + const ctx: any = { config: { url: 'https://example.com' }, - relative_url: require('../../../dist/plugins/helper/relative_url') + relative_url: relativeUrlHelper }; - const urlFor = require('../../../dist/plugins/helper/url_for').bind(ctx); + const urlFor: (...args: UrlForHelperParams) => UrlForHelperReturn = urlForHelper.bind(ctx); it('should encode path', () => { ctx.config.root = '/'; @@ -50,7 +53,7 @@ describe('url_for', () => { ctx.config.relative_link = false; }); - it('internel url (pretty_urls.trailing_index disabled)', () => { + it('internal url (pretty_urls.trailing_index disabled)', () => { ctx.config.pretty_urls = { trailing_index: false }; ctx.path = ''; ctx.config.root = '/'; diff --git a/test/scripts/hexo/hexo.js b/test/scripts/hexo/hexo.ts similarity index 96% rename from test/scripts/hexo/hexo.js rename to test/scripts/hexo/hexo.ts index b039ec1fb0..9dfae90aaf 100644 --- a/test/scripts/hexo/hexo.js +++ b/test/scripts/hexo/hexo.ts @@ -1,15 +1,16 @@ -'use strict'; - -const { sep, join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); -const { spy } = require('sinon'); -const testUtil = require('../../util'); -const { full_url_for } = require('hexo-util'); +import { sep, join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import { spy } from 'sinon'; +import { readStream } from '../../util'; +import { full_url_for } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('Hexo', () => { const base_dir = join(__dirname, 'hexo_test'); - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(base_dir, { silent: true }); const coreDir = join(__dirname, '../../..'); const { version } = require('../../../package.json'); @@ -19,12 +20,12 @@ describe('Hexo', () => { const { route } = hexo; async function checkStream(stream, expected) { - const data = await testUtil.stream.read(stream); + const data = await readStream(stream); data.should.eql(expected); } function loadAssetGenerator() { - hexo.extend.generator.register('asset', require('../../../dist/plugins/generator/asset')); + hexo.extend.generator.register('asset', require('../../../lib/plugins/generator/asset')); } before(async () => { @@ -48,7 +49,7 @@ describe('Hexo', () => { /* eslint-disable no-path-concat */ hexo.core_dir.should.eql(coreDir + sep); - hexo.lib_dir.should.eql(join(coreDir, 'dist') + sep); + hexo.lib_dir.should.eql(join(coreDir, 'lib') + sep); hexo.version.should.eql(version); hexo.base_dir.should.eql(__dirname + sep); hexo.public_dir.should.eql(join(__dirname, 'public') + sep); @@ -70,7 +71,7 @@ describe('Hexo', () => { hexo.config_path.should.eql(join(__dirname, '_config.yml')); }); - it('constructs mutli-config', () => { + it('constructs multi-config', () => { const configs = ['../../../fixtures/_config.json', '../../../fixtures/_config.json']; const args = { _: [], config: configs.join(',') }; const hexo = new Hexo(base_dir, args); @@ -167,7 +168,7 @@ describe('Hexo', () => { themeConfig.a.b.should.eql(3); const Locals = hexo._generateLocals(); - const { theme: themeLocals } = new Locals(); + const { theme: themeLocals } = new Locals('', {path: '', layout: [], data: {}}); themeLocals.a.should.have.own.property('c'); themeLocals.a.b.should.eql(3); @@ -186,7 +187,7 @@ describe('Hexo', () => { themeConfig.c.should.eql(3); const Locals = hexo._generateLocals(); - const { theme: themeLocals } = new Locals(); + const { theme: themeLocals } = new Locals('', {path: '', layout: [], data: {}}); themeLocals.should.have.own.property('c'); themeLocals.c.should.eql(3); @@ -530,6 +531,7 @@ describe('Hexo', () => { }); it('_generate() - return nothing in generator', async () => { + // @ts-ignore hexo.extend.generator.register('test_nothing', () => { // }); diff --git a/test/scripts/hexo/index.js b/test/scripts/hexo/index.js deleted file mode 100644 index 94c443d65a..0000000000 --- a/test/scripts/hexo/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -describe('Core', () => { - require('./hexo'); - require('./load_config'); - require('./validate_config'); - require('./load_database'); - require('./load_plugins'); - require('./load_theme_config'); - require('./locals'); - require('./multi_config_path'); - require('./post'); - require('./render'); - require('./router'); - require('./scaffold'); - require('./update_package'); -}); diff --git a/test/scripts/hexo/load_config.js b/test/scripts/hexo/load_config.ts similarity index 94% rename from test/scripts/hexo/load_config.js rename to test/scripts/hexo/load_config.ts index 05150ff1ba..64e0536e62 100644 --- a/test/scripts/hexo/load_config.js +++ b/test/scripts/hexo/load_config.ts @@ -1,15 +1,12 @@ -'use strict'; - -const { join, sep, resolve } = require('path'); -const { writeFile, unlink, mkdirs, rmdir } = require('hexo-fs'); -const { makeRe } = require('micromatch'); +import { join, sep, resolve } from 'path'; +import { writeFile, unlink, mkdirs, rmdir } from 'hexo-fs'; +import { makeRe } from 'micromatch'; +import loadConfig from '../../../lib/hexo/load_config'; +import defaultConfig from '../../../lib/hexo/default_config'; +import Hexo from '../../../lib/hexo'; describe('Load config', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'config_test'), { silent: true }); - const loadConfig = require('../../../dist/hexo/load_config'); - const defaultConfig = require('../../../dist/hexo/default_config'); - hexo.env.init = true; before(() => mkdirs(hexo.base_dir).then(() => hexo.init())); diff --git a/test/scripts/hexo/load_database.js b/test/scripts/hexo/load_database.ts similarity index 83% rename from test/scripts/hexo/load_database.js rename to test/scripts/hexo/load_database.ts index 27c257e9be..9093113f52 100644 --- a/test/scripts/hexo/load_database.js +++ b/test/scripts/hexo/load_database.ts @@ -1,12 +1,10 @@ -'use strict'; - -const { join } = require('path'); -const { exists, mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); +import { join } from 'path'; +import Hexo from '../../../lib/hexo'; +import { exists, mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +import loadDatabase from '../../../lib/hexo/load_database'; describe('Load database', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'db_test'), {silent: true}); - const loadDatabase = require('../../../dist/hexo/load_database'); const dbPath = hexo.database.options.path; const fixture = { @@ -63,9 +61,7 @@ describe('Load database', () => { // Clean-up is not necessary (unlike the above tests), // because the db file is already removed if invalid describe('Load database - load failed', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname), {silent: true}); - const loadDatabase = require('../../../dist/hexo/load_database'); const dbPath = hexo.database.options.path; it('database load failed', async () => { diff --git a/test/scripts/hexo/load_plugins.js b/test/scripts/hexo/load_plugins.ts similarity index 79% rename from test/scripts/hexo/load_plugins.js rename to test/scripts/hexo/load_plugins.ts index 50dd9620b3..3446114e7e 100644 --- a/test/scripts/hexo/load_plugins.js +++ b/test/scripts/hexo/load_plugins.ts @@ -1,13 +1,14 @@ -'use strict'; - -const fs = require('hexo-fs'); -const { join, dirname } = require('path'); -const Promise = require('bluebird'); +import { join, dirname } from 'path'; +import { writeFile, mkdir, rmdir, unlink } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import loadPlugins from '../../../lib/hexo/load_plugins'; +// @ts-ignore +import Promise from 'bluebird'; +import chai from 'chai'; +const should = chai.should(); describe('Load plugins', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(join(__dirname, 'plugin_test'), { silent: true }); - const loadPlugins = require('../../../dist/hexo/load_plugins'); + const hexo = new Hexo(join(__dirname, 'plugin_test'), { silent: true }) as any; const script = [ 'hexo._script_test = {', @@ -41,7 +42,7 @@ describe('Load plugins', () => { delete hexo._script_test; } - function createPackageFile(name, path) { + function createPackageFile(name, path?) { const pkg = { name: 'hexo-site', version: '0.0.0', @@ -52,7 +53,7 @@ describe('Load plugins', () => { }; path = path || join(hexo.base_dir, 'package.json'); - return fs.writeFile(path, JSON.stringify(pkg, null, ' ')); + return writeFile(path, JSON.stringify(pkg, null, ' ')); } function createPackageFileWithDevDeps(name) { @@ -66,15 +67,15 @@ describe('Load plugins', () => { } }; - return fs.writeFile(join(hexo.base_dir, 'package.json'), JSON.stringify(pkg, null, ' ')); + return writeFile(join(hexo.base_dir, 'package.json'), JSON.stringify(pkg, null, ' ')); } hexo.env.init = true; hexo.theme_script_dir = join(hexo.base_dir, 'themes', 'test', 'scripts'); - before(() => fs.mkdir(hexo.base_dir)); + before(() => mkdir(hexo.base_dir)); - after(() => fs.rmdir(hexo.base_dir)); + after(() => rmdir(hexo.base_dir)); afterEach(async () => { await createPackageFile('hexo-another-plugin'); @@ -86,10 +87,10 @@ describe('Load plugins', () => { return Promise.all([ createPackageFile(name), - fs.writeFile(path, script) + writeFile(path, script) ]).then(() => loadPlugins(hexo)).then(() => { validate(path); - return fs.unlink(path); + return unlink(path); }); }); @@ -99,10 +100,10 @@ describe('Load plugins', () => { return Promise.all([ createPackageFile(name), - fs.writeFile(path, asyncScript) + writeFile(path, asyncScript) ]).then(() => loadPlugins(hexo)).then(() => { validate(path); - return fs.unlink(path); + return unlink(path); }); }); @@ -112,10 +113,10 @@ describe('Load plugins', () => { return Promise.all([ createPackageFile(name), - fs.writeFile(path, script) + writeFile(path, script) ]).then(() => loadPlugins(hexo)).then(() => { validate(path); - return fs.unlink(path); + return unlink(path); }); }); @@ -125,10 +126,10 @@ describe('Load plugins', () => { return Promise.all([ createPackageFileWithDevDeps(name), - fs.writeFile(path, script) + writeFile(path, script) ]).then(() => loadPlugins(hexo)).then(() => { validate(path); - return fs.unlink(path); + return unlink(path); }); }); @@ -137,10 +138,10 @@ describe('Load plugins', () => { const path = join(hexo.plugin_dir, name, 'index.js'); return Promise.all([ createPackageFile(name, join(hexo.theme_dir, 'package.json')), - fs.writeFile(path, script) + writeFile(path, script) ]).then(() => loadPlugins(hexo)).then(() => { validate(path); - return fs.unlink(path); + return unlink(path); }); }); @@ -151,13 +152,13 @@ describe('Load plugins', () => { await Promise.all([ createPackageFile(name), - fs.writeFile(path, script) + writeFile(path, script) ]); await loadPlugins(hexo); should.not.exist(hexo._script_test); delete hexo.config.theme; - return fs.unlink(path); + return unlink(path); }); it('ignore scoped plugin whose name is started with "hexo-theme-"', async () => { @@ -167,13 +168,13 @@ describe('Load plugins', () => { await Promise.all([ createPackageFile(name), - fs.writeFile(path, script) + writeFile(path, script) ]); await loadPlugins(hexo); should.not.exist(hexo._script_test); delete hexo.config.theme; - return fs.unlink(path); + return unlink(path); }); it('ignore plugins whose name is not started with "hexo-"', async () => { @@ -183,12 +184,12 @@ describe('Load plugins', () => { await Promise.all([ createPackageFile(name), - fs.writeFile(path, script) + writeFile(path, script) ]); await loadPlugins(hexo); should.not.exist(hexo._script_test); - return fs.unlink(path); + return unlink(path); }); it('ignore plugins which is typescript definition', () => { @@ -198,10 +199,10 @@ describe('Load plugins', () => { return Promise.all([ createPackageFile(name), - fs.writeFile(path, script) + writeFile(path, script) ]).then(() => loadPlugins(hexo)).then(() => { should.not.exist(hexo._script_test); - return fs.unlink(path); + return unlink(path); }); }); @@ -210,19 +211,19 @@ describe('Load plugins', () => { it('load scripts', async () => { const path = join(hexo.script_dir, 'test.js'); - fs.writeFile(path, script); + writeFile(path, script); await loadPlugins(hexo); validate(path); - return fs.unlink(path); + return unlink(path); }); it('load theme scripts', () => { const path = join(hexo.theme_script_dir, 'test.js'); - return fs.writeFile(path, script).then(() => loadPlugins(hexo)).then(() => { + return writeFile(path, script).then(() => loadPlugins(hexo)).then(() => { validate(path); - return fs.unlink(path); + return unlink(path); }); }); @@ -230,13 +231,13 @@ describe('Load plugins', () => { const script = 'hexo._script_test = true'; const path = join(hexo.script_dir, 'test.js'); - return fs.writeFile(path, script).then(() => { + return writeFile(path, script).then(() => { hexo.env.safe = true; return loadPlugins(hexo); }).then(() => { hexo.env.safe = false; should.not.exist(hexo._script_test); - return fs.unlink(path); + return unlink(path); }); }); @@ -251,10 +252,10 @@ describe('Load plugins', () => { '//# sourceMappingURL=data:application/json;' ].join('\n'); - fs.writeFile(path, script); + writeFile(path, script); await loadPlugins(hexo); hexo._script_test.should.eql(true); - return fs.unlink(path); + return unlink(path); }); }); diff --git a/test/scripts/hexo/load_theme_config.js b/test/scripts/hexo/load_theme_config.ts similarity index 90% rename from test/scripts/hexo/load_theme_config.js rename to test/scripts/hexo/load_theme_config.ts index 7dc742305b..98adb65401 100644 --- a/test/scripts/hexo/load_theme_config.js +++ b/test/scripts/hexo/load_theme_config.ts @@ -1,12 +1,12 @@ -'use strict'; - -const { join } = require('path'); -const { mkdirs, unlink, writeFile, rmdir } = require('hexo-fs'); +import { join } from 'path'; +import { mkdirs, unlink, writeFile, rmdir } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('Load alternate theme config', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'config_test'), {silent: true}); - const loadThemeConfig = require('../../../dist/hexo/load_theme_config'); + const loadThemeConfig = require('../../../lib/hexo/load_theme_config'); hexo.env.init = true; @@ -20,6 +20,7 @@ describe('Load alternate theme config', () => { }); it('hexo.config.theme does not exist', async () => { + // @ts-ignore hexo.config.theme = undefined; await loadThemeConfig(hexo); hexo.config.theme_config.foo.bar.should.eql('ahhhhhh'); diff --git a/test/scripts/hexo/locals.js b/test/scripts/hexo/locals.ts similarity index 89% rename from test/scripts/hexo/locals.js rename to test/scripts/hexo/locals.ts index 9276b5ccaa..3fb483aef6 100644 --- a/test/scripts/hexo/locals.js +++ b/test/scripts/hexo/locals.ts @@ -1,10 +1,12 @@ -'use strict'; +import Locals from '../../../lib/hexo/locals'; +import chai from 'chai'; +const should = chai.should(); describe('Locals', () => { - const Locals = require('../../../dist/hexo/locals'); const locals = new Locals(); it('get() - name must be a string', () => { + // @ts-ignore should.throw(() => locals.get(), 'name must be a string!'); }); @@ -24,10 +26,12 @@ describe('Locals', () => { }); it('set() - name must be a string', () => { + // @ts-ignore should.throw(() => locals.set(), 'name must be a string!'); }); it('set() - value is required', () => { + // @ts-ignore should.throw(() => locals.set('test'), 'value is required!'); }); @@ -41,6 +45,7 @@ describe('Locals', () => { }); it('remove() - name must be a string', () => { + // @ts-ignore should.throw(() => locals.remove(), 'name must be a string!'); }); diff --git a/test/scripts/hexo/multi_config_path.js b/test/scripts/hexo/multi_config_path.ts similarity index 86% rename from test/scripts/hexo/multi_config_path.js rename to test/scripts/hexo/multi_config_path.ts index 3d6cd423b7..dd7ad4202a 100644 --- a/test/scripts/hexo/multi_config_path.js +++ b/test/scripts/hexo/multi_config_path.ts @@ -1,15 +1,14 @@ -'use strict'; - -const pathFn = require('path'); -const osFn = require('os'); -const fs = require('hexo-fs'); -const yml = require('js-yaml'); +import pathFn from 'path'; +import osFn from 'os'; +import { writeFileSync, rmdirSync, unlinkSync, readFileSync } from 'hexo-fs'; +import yml from 'js-yaml'; +import Hexo from '../../../lib/hexo'; +import multiConfigPath from '../../../lib/hexo/multi_config_path'; describe('config flag handling', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(pathFn.join(__dirname, 'test_dir')); + const hexo = new Hexo(pathFn.join(__dirname, 'test_dir')) as any; - const mcp = require('../../../dist/hexo/multi_config_path')(hexo); + const mcp = multiConfigPath(hexo); const base = hexo.base_dir; function ConsoleReader() { @@ -125,13 +124,13 @@ describe('config flag handling', () => { ].join('\n'); before(() => { - fs.writeFileSync(base + 'test1.yml', testYaml1); - fs.writeFileSync(base + 'test2.yml', testYaml2); - fs.writeFileSync(base + 'test1.json', testJson1); - fs.writeFileSync(base + 'test2.json', testJson2); + writeFileSync(base + 'test1.yml', testYaml1); + writeFileSync(base + 'test2.yml', testYaml2); + writeFileSync(base + 'test1.json', testJson1); + writeFileSync(base + 'test2.json', testJson2); // not supported type - fs.writeFileSync(base + 'test1.xml', ''); - fs.writeFileSync('/tmp/test3.json', testJson3); + writeFileSync(base + 'test1.xml', ''); + writeFileSync('/tmp/test3.json', testJson3); }); afterEach(() => { @@ -139,8 +138,8 @@ describe('config flag handling', () => { }); after(() => { - fs.rmdirSync(hexo.base_dir); - fs.unlinkSync('/tmp/test3.json'); + rmdirSync(hexo.base_dir); + unlinkSync('/tmp/test3.json'); }); it('no file', () => { @@ -215,14 +214,14 @@ describe('config flag handling', () => { it('2 YAML overwrite', () => { const configFile = mcp(base, 'test1.yml,test2.yml'); - let config = fs.readFileSync(configFile); + let config: any = readFileSync(configFile); config = yml.load(config); config.author.should.eql('bar'); config.favorites.food.should.eql('candy'); config.type.should.eql('dinosaur'); - config = fs.readFileSync(mcp(base, 'test2.yml,test1.yml')); + config = readFileSync(mcp(base, 'test2.yml,test1.yml')); config = yml.load(config); config.author.should.eql('foo'); @@ -231,14 +230,14 @@ describe('config flag handling', () => { }); it('2 JSON overwrite', () => { - let config = fs.readFileSync(mcp(base, 'test1.json,test2.json')); + let config: any = readFileSync(mcp(base, 'test1.json,test2.json')); config = yml.load(config); config.author.should.eql('waldo'); config.favorites.food.should.eql('ice cream'); config.type.should.eql('elephant'); - config = fs.readFileSync(mcp(base, 'test2.json,test1.json')); + config = readFileSync(mcp(base, 'test2.json,test1.json')); config = yml.load(config); config.author.should.eql('dinosaur'); @@ -247,14 +246,14 @@ describe('config flag handling', () => { }); it('JSON & YAML overwrite', () => { - let config = fs.readFileSync(mcp(base, 'test1.yml,test1.json')); + let config: any = readFileSync(mcp(base, 'test1.yml,test1.json')); config = yml.load(config); config.author.should.eql('dinosaur'); config.favorites.food.should.eql('burgers'); config.type.should.eql('elephant'); - config = fs.readFileSync(mcp(base, 'test1.json,test1.yml')); + config = readFileSync(mcp(base, 'test1.json,test1.yml')); config = yml.load(config); config.author.should.eql('foo'); @@ -274,7 +273,7 @@ describe('config flag handling', () => { mcp(base, 'notafile.yml,alsonotafile.json', outputPath).should.not.eql(combinedPath); // delete /tmp/_multiconfig.yml - fs.unlinkSync(combinedPath); + unlinkSync(combinedPath); hexo.log.reader[1].type.should.eql('debug'); hexo.log.reader[1].msg.should.eql(`Writing _multiconfig.yml to ${combinedPath}`); diff --git a/test/scripts/hexo/post.js b/test/scripts/hexo/post.ts similarity index 91% rename from test/scripts/hexo/post.js rename to test/scripts/hexo/post.ts index 109bf2367b..b01e41d61f 100644 --- a/test/scripts/hexo/post.js +++ b/test/scripts/hexo/post.ts @@ -1,18 +1,18 @@ -'use strict'; - -const { join } = require('path'); -const moment = require('moment'); -const { readFile, mkdirs, unlink, rmdir, writeFile, exists, stat, listDir } = require('hexo-fs'); -const { highlight } = require('hexo-util'); -const { spy, useFakeTimers } = require('sinon'); -const { parse: yfm } = require('hexo-front-matter'); -const fixture = require('../../fixtures/post_render'); +import { join } from 'path'; +import moment from 'moment'; +import { readFile, mkdirs, unlink, rmdir, writeFile, exists, stat, listDir } from 'hexo-fs'; +import { spy, useFakeTimers } from 'sinon'; +import { parse as yfm } from 'hexo-front-matter'; +import { expected, content, expected_disable_nunjucks, content_for_issue_3346, expected_for_issue_3346, content_for_issue_4460 } from '../../fixtures/post_render'; +import { highlight } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); const escapeSwigTag = str => str.replace(/{/g, '{').replace(/}/g, '}'); describe('Post', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'post_test')); - require('../../../dist/plugins/highlight/')(hexo); + require('../../../lib/plugins/highlight/')(hexo); const { post } = hexo; const now = Date.now(); let clock; @@ -444,7 +444,7 @@ describe('Post', () => { try { post.path.should.eql(path); post.content.should.eql(content); - readFile(path).asCallback((err, data) => { + readFile(path).asCallback((err, data: any) => { if (err) { done(err); return; @@ -658,18 +658,18 @@ describe('Post', () => { hexo.extend.filter.register('before_post_render', beforeHook); hexo.extend.filter.register('after_post_render', afterHook); - const data = await post.render(null, { - content: fixture.content, + const data = await post.render('', { + content, engine: 'markdown' }); - data.content.trim().should.eql(fixture.expected); + data.content.trim().should.eql(expected); beforeHook.calledOnce.should.be.true; afterHook.calledOnce.should.be.true; }); it('render() - callback', done => { - post.render(null, { - content: fixture.content, + post.render('', { + content, engine: 'markdown' }, err => { done(err); @@ -689,7 +689,7 @@ describe('Post', () => { it('render() - skip js', async () => { const content = 'let a = "{{ 1 + 1 }}"'; - const data = await post.render(null, { + const data = await post.render('', { content, source: 'render_test.js' }); @@ -699,7 +699,7 @@ describe('Post', () => { it('render() - toString', async () => { const content = 'foo: 1'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'yaml' }); @@ -713,7 +713,7 @@ describe('Post', () => { '{% endquote %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'njk' }); @@ -737,7 +737,7 @@ describe('Post', () => { '{% endcode %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content }); data.content.trim().should.eql([ @@ -750,7 +750,7 @@ describe('Post', () => { it('render() - recover escaped nunjucks blocks which is html escaped', async () => { const content = '`{% raw %}{{ test }}{% endraw %}`, {%raw%}{{ test }}{%endraw%}'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -764,7 +764,7 @@ describe('Post', () => { hexo.extend.filter.register('after_render:html', filter); - await post.render(null, { + await post.render('', { content, engine: 'markdown' }); @@ -774,7 +774,7 @@ describe('Post', () => { }); it('render() - callback - not path and file', callback => { - post.render(null, {}, (err, result) => { + post.render('', {}, (err, result) => { try { err.should.be.exist; err.should.be.instanceof(Error); @@ -794,11 +794,11 @@ describe('Post', () => { renderer.disableNunjucks = true; try { - const data = await post.render(null, { - content: fixture.content, + const data = await post.render('', { + content, engine: 'markdown' }); - data.content.trim().should.eql(fixture.expected_disable_nunjucks); + data.content.trim().should.eql(expected_disable_nunjucks); } finally { renderer.disableNunjucks = false; } @@ -810,11 +810,11 @@ describe('Post', () => { renderer.disableNunjucks = false; try { - const data = await post.render(null, { - content: fixture.content, + const data = await post.render('', { + content, engine: 'markdown' }); - data.content.trim().should.eql(fixture.expected); + data.content.trim().should.eql(expected); } finally { renderer.disableNunjucks = false; } @@ -827,7 +827,7 @@ describe('Post', () => { loremFn.disableNunjucks = true; hexo.extend.renderer.register('coffee', 'js', loremFn, true); - const data = await post.render(null, { content, engine: 'coffee' }); + const data = await post.render('', { content, engine: 'coffee' }); data.content.should.eql(content.toUpperCase()); }); @@ -838,7 +838,7 @@ describe('Post', () => { loremFn.disableNunjucks = false; hexo.extend.renderer.register('coffee', 'js', loremFn, true); - const data = await post.render(null, { content, engine: 'coffee' }); + const data = await post.render('', { content, engine: 'coffee' }); data.content.should.not.eql(content.toUpperCase()); }); @@ -847,12 +847,12 @@ describe('Post', () => { renderer.disableNunjucks = true; try { - const data = await post.render(null, { - content: fixture.content, + const data = await post.render('', { + content, engine: 'markdown', disableNunjucks: false }); - data.content.trim().should.eql(fixture.expected); + data.content.trim().should.eql(expected); } finally { renderer.disableNunjucks = false; } @@ -863,12 +863,12 @@ describe('Post', () => { renderer.disableNunjucks = false; try { - const data = await post.render(null, { - content: fixture.content, + const data = await post.render('', { + content, engine: 'markdown', disableNunjucks: true }); - data.content.trim().should.eql(fixture.expected_disable_nunjucks); + data.content.trim().should.eql(expected_disable_nunjucks); } finally { renderer.disableNunjucks = false; } @@ -880,12 +880,13 @@ describe('Post', () => { renderer.disableNunjucks = true; try { - const data = await post.render(null, { - content: fixture.content, + const data = await post.render('', { + content, engine: 'markdown', + // @ts-ignore disableNunjucks: null }); - data.content.trim().should.eql(fixture.expected_disable_nunjucks); + data.content.trim().should.eql(expected_disable_nunjucks); } finally { renderer.disableNunjucks = false; } @@ -902,7 +903,7 @@ describe('Post', () => { '{% endblockquote %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -917,7 +918,7 @@ describe('Post', () => { it('render() - swig comments', async () => { const content = '{# blockquote #}'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -933,7 +934,7 @@ describe('Post', () => { '\\end{equation}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -957,7 +958,7 @@ describe('Post', () => { '{% endblockquote %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content }); data.content.trim().should.eql([ @@ -983,7 +984,7 @@ describe('Post', () => { ...quotedContent.map(s => '> ' + s) ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1013,7 +1014,7 @@ describe('Post', () => { ...quotedContent.map(s => '> ' + s) ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1045,7 +1046,7 @@ describe('Post', () => { ...quotedContent.map(s => '> ' + s) ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1094,7 +1095,7 @@ describe('Post', () => { ...quotedContent.map(addQuote) ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1120,7 +1121,7 @@ describe('Post', () => { '{% pullquote %}content2{% endpullquote %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1141,7 +1142,7 @@ describe('Post', () => { '{% pullquote center %}content2{% endpullquote %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1154,14 +1155,14 @@ describe('Post', () => { // #3346 it('render() - swig tag inside backtick code block', async () => { - const content = fixture.content_for_issue_3346; + const content = content_for_issue_3346; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); - data.content.trim().should.eql(fixture.expected_for_issue_3346); + data.content.trim().should.eql(expected_for_issue_3346); }); // test for https://github.com/hexojs/hexo/pull/4171#issuecomment-594412367 @@ -1189,7 +1190,7 @@ describe('Post', () => { '{% pullquote warning %}Text{% endpullquote %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1205,7 +1206,7 @@ describe('Post', () => { it('render() - "{{" & "}}" inside inline code', async () => { const content = 'In Go\'s templates, blocks look like this: `{{block "template name" .}} (content) {{end}}`.'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1217,7 +1218,7 @@ describe('Post', () => { it('render() - swig var inside inline code', async () => { const content = '`{{ 1 + 1 }}` {{ 1 + 1 }}'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1245,7 +1246,7 @@ describe('Post', () => { '```' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1270,7 +1271,7 @@ describe('Post', () => { '{% endraw %}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1304,7 +1305,7 @@ describe('Post', () => { '' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1327,7 +1328,7 @@ describe('Post', () => { '```' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1342,9 +1343,9 @@ describe('Post', () => { it('render() - issue #4460', async () => { hexo.config.syntax_highlighter = 'prismjs'; - const content = fixture.content_for_issue_4460; + const content = content_for_issue_4460; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1359,7 +1360,7 @@ describe('Post', () => { const content = 'Disable rendering of Nunjucks tag `{{ }}` / `{% %}`'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1371,10 +1372,10 @@ describe('Post', () => { }); // https://github.com/hexojs/hexo/issues/5301 - it('render() - dont escape uncomplete tags', async () => { + it('render() - dont escape incomplete tags', async () => { const content = 'dont drop `{% }` 11111 `{# }` 22222 `{{ }` 33333'; - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); @@ -1385,11 +1386,11 @@ describe('Post', () => { data.content.should.not.contains('`'); // ` }); - it('render() - uncomplete tags throw error', async () => { - const content = 'nunjucks should thorw {# } error'; + it('render() - incomplete tags throw error', async () => { + const content = 'nunjucks should throw {# } error'; try { - await post.render(null, { + await post.render('', { content, engine: 'markdown' }); @@ -1407,7 +1408,7 @@ describe('Post', () => { '%}' ].join('\n'); - const data = await post.render(null, { + const data = await post.render('', { content, engine: 'markdown' }); diff --git a/test/scripts/hexo/render.js b/test/scripts/hexo/render.ts similarity index 96% rename from test/scripts/hexo/render.js rename to test/scripts/hexo/render.ts index 5ebb6f16db..b13a9d13f8 100644 --- a/test/scripts/hexo/render.js +++ b/test/scripts/hexo/render.ts @@ -1,12 +1,12 @@ -'use strict'; - -const { writeFile, rmdir } = require('hexo-fs'); -const { join } = require('path'); -const yaml = require('js-yaml'); -const { spy, assert: sinonAssert } = require('sinon'); +import { writeFile, rmdir } from 'hexo-fs'; +import { join } from 'path'; +import yaml from 'js-yaml'; +import { spy, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('Render', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'render_test')); hexo.config.meta_generator = false; @@ -97,6 +97,7 @@ describe('Render', () => { it('render() - no path and text', async () => { try { + // @ts-ignore await hexo.render.render(); should.fail('Return value must be rejected'); } catch (err) { @@ -106,6 +107,7 @@ describe('Render', () => { it('render() - null path and text', async () => { try { + // @ts-ignore await hexo.render.render({text: null, engine: null}); should.fail('Return value must be rejected'); } catch (err) { @@ -234,10 +236,12 @@ describe('Render', () => { }); it('renderSync() - no path and text', () => { + // @ts-ignore should.throw(() => hexo.render.renderSync(), 'No input file or string!'); }); it('renderSync() - null path and text', () => { + // @ts-ignore should.throw(() => hexo.render.renderSync({text: null, engine: null}), 'No input file or string!'); }); @@ -294,6 +298,7 @@ describe('Render', () => { const result = hexo.render.renderSync(data); filter.calledOnce.should.be.true; + // @ts-ignore sinonAssert.calledWith(filter, data.text, data); result.should.eql(data.text.trim()); diff --git a/test/scripts/hexo/router.js b/test/scripts/hexo/router.ts similarity index 88% rename from test/scripts/hexo/router.js rename to test/scripts/hexo/router.ts index 5e590ee8f3..5683a13636 100644 --- a/test/scripts/hexo/router.js +++ b/test/scripts/hexo/router.ts @@ -1,19 +1,20 @@ -'use strict'; - -const Promise = require('bluebird'); -const { Readable } = require('stream'); -const { join } = require('path'); -const crypto = require('crypto'); -const { createReadStream } = require('hexo-fs'); -const { spy, assert: sinonAssert } = require('sinon'); -const testUtil = require('../../util'); +// @ts-ignore +import Promise from 'bluebird'; +import { Readable } from 'stream'; +import { join } from 'path'; +import crypto from 'crypto'; +import { createReadStream } from 'hexo-fs'; +import { spy, assert as sinonAssert } from 'sinon'; +import { readStream } from '../../util'; +import Router from '../../../lib/hexo/router'; +import chai from 'chai'; +const should = chai.should(); describe('Router', () => { - const Router = require('../../../dist/hexo/router'); const router = new Router(); function checkStream(stream, expected) { - return testUtil.stream.read(stream).then(data => { + return readStream(stream).then(data => { data.should.eql(expected); }); } @@ -57,6 +58,7 @@ describe('Router', () => { }); it('format() - path must be a string', () => { + // @ts-ignore should.throw(() => router.format(() => {}), 'path must be a string!'); }); @@ -109,10 +111,12 @@ describe('Router', () => { }); it('set() - path must be a string', () => { + // @ts-ignore should.throw(() => router.set(), 'path must be a string!'); }); it('set() - data is required', () => { + // @ts-ignore should.throw(() => router.set('test'), 'data is required!'); }); @@ -121,7 +125,7 @@ describe('Router', () => { throw new Error('error test'); }); - return testUtil.stream.read(router.get('test')).then(() => { + return readStream(router.get('test')).then(() => { should.fail('Return value must be rejected'); }, err => { err.should.have.property('message', 'error test'); @@ -153,12 +157,13 @@ describe('Router', () => { return Promise.all([ checksum(router.get('test')), checksum(createReadStream(path)) - ]).then(data => { + ]).then((data: any) => { data[0].should.eql(data[1]); }); }); it('get() - path must be a string', () => { + // @ts-ignore should.throw(() => router.get(), 'path must be a string!'); }); @@ -187,6 +192,7 @@ describe('Router', () => { }); it('isModified() - path must be a string', () => { + // @ts-ignore should.throw(() => router.isModified(), 'path must be a string!'); }); @@ -203,6 +209,7 @@ describe('Router', () => { }); it('remove() - path must be a string', () => { + // @ts-ignore should.throw(() => router.remove(), 'path must be a string!'); }); }); diff --git a/test/scripts/hexo/scaffold.js b/test/scripts/hexo/scaffold.ts similarity index 89% rename from test/scripts/hexo/scaffold.js rename to test/scripts/hexo/scaffold.ts index 0f432aad7f..c181d2d2de 100644 --- a/test/scripts/hexo/scaffold.js +++ b/test/scripts/hexo/scaffold.ts @@ -1,10 +1,10 @@ -'use strict'; - -const { join } = require('path'); -const { exists, readFile, rmdir, unlink, writeFile } = require('hexo-fs'); +import { join } from 'path'; +import { exists, readFile, rmdir, unlink, writeFile } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('Scaffold', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); const scaffold = hexo.scaffold; const scaffoldDir = hexo.scaffold_dir; diff --git a/test/scripts/hexo/update_package.js b/test/scripts/hexo/update_package.ts similarity index 79% rename from test/scripts/hexo/update_package.js rename to test/scripts/hexo/update_package.ts index fac448627f..b2b440bcd9 100644 --- a/test/scripts/hexo/update_package.js +++ b/test/scripts/hexo/update_package.ts @@ -1,12 +1,10 @@ -'use strict'; - -const { join } = require('path'); -const { readFile, unlink, writeFile } = require('hexo-fs'); +import { join } from 'path'; +import { readFile, unlink, writeFile } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import updatePkg from '../../../lib/hexo/update_package'; describe('Update package.json', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname, {silent: true}); - const updatePkg = require('../../../dist/hexo/update_package'); const packagePath = join(hexo.base_dir, 'package.json'); beforeEach(() => { @@ -27,7 +25,7 @@ describe('Update package.json', () => { await writeFile(packagePath, JSON.stringify(pkg)); await updatePkg(hexo); - const content = await readFile(packagePath); + const content = await readFile(packagePath) as string; JSON.parse(content).hexo.version.should.eql(hexo.version); hexo.env.init.should.be.true; @@ -42,7 +40,7 @@ describe('Update package.json', () => { await writeFile(packagePath, JSON.stringify(pkg)); await updatePkg(hexo); - const content = await readFile(packagePath); + const content = await readFile(packagePath) as string; // Don't change the original package.json JSON.parse(content).should.eql(pkg); hexo.env.init.should.be.false; @@ -59,7 +57,7 @@ describe('Update package.json', () => { await writeFile(packagePath, JSON.stringify(pkg)); await updatePkg(hexo); - const content = await readFile(packagePath); + const content = await readFile(packagePath) as string; JSON.parse(content).should.eql(pkg); hexo.env.init.should.be.true; diff --git a/test/scripts/hexo/validate_config.js b/test/scripts/hexo/validate_config.ts similarity index 87% rename from test/scripts/hexo/validate_config.js rename to test/scripts/hexo/validate_config.ts index be5a9bbdb8..c414c2a68d 100644 --- a/test/scripts/hexo/validate_config.js +++ b/test/scripts/hexo/validate_config.ts @@ -1,12 +1,12 @@ -'use strict'; - -const { spy } = require('sinon'); +import { spy } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import validateConfig from '../../../lib/hexo/validate_config'; +import defaultConfig from '../../../lib/hexo/default_config'; +import chai from 'chai'; +const should = chai.should(); describe('Validate config', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - const validateConfig = require('../../../dist/hexo/validate_config'); - const defaultConfig = require('../../../dist/hexo/default_config'); let logSpy; beforeEach(() => { @@ -17,6 +17,7 @@ describe('Validate config', () => { }); it('config.url - undefined', () => { + // @ts-ignore delete hexo.config.url; try { @@ -29,6 +30,7 @@ describe('Validate config', () => { }); it('config.url - wrong type', () => { + // @ts-ignore hexo.config.url = true; try { @@ -66,6 +68,7 @@ describe('Validate config', () => { }); it('config.root - undefined', () => { + // @ts-ignore delete hexo.config.root; try { @@ -78,6 +81,7 @@ describe('Validate config', () => { }); it('config.root - wrong type', () => { + // @ts-ignore hexo.config.root = true; try { diff --git a/test/scripts/models/asset.js b/test/scripts/models/asset.ts similarity index 90% rename from test/scripts/models/asset.js rename to test/scripts/models/asset.ts index 889ba9738e..8af26c8659 100644 --- a/test/scripts/models/asset.js +++ b/test/scripts/models/asset.ts @@ -1,9 +1,7 @@ -'use strict'; - -const { join } = require('path'); +import { join } from 'path'; +import Hexo from '../../../lib/hexo'; describe('Asset', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Asset = hexo.model('Asset'); diff --git a/test/scripts/models/cache.js b/test/scripts/models/cache.ts similarity index 81% rename from test/scripts/models/cache.js rename to test/scripts/models/cache.ts index de8ad9d7c9..b9dbc66ab4 100644 --- a/test/scripts/models/cache.js +++ b/test/scripts/models/cache.ts @@ -1,7 +1,6 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; describe('Cache', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Cache = hexo.model('Cache'); diff --git a/test/scripts/models/category.js b/test/scripts/models/category.ts similarity index 96% rename from test/scripts/models/category.js rename to test/scripts/models/category.ts index d1a0da40a1..c0b0009b10 100644 --- a/test/scripts/models/category.js +++ b/test/scripts/models/category.ts @@ -1,14 +1,12 @@ -'use strict'; - -const { deepMerge, full_url_for } = require('hexo-util'); +import { deepMerge, full_url_for } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import defaults from '../../../lib/hexo/default_config'; describe('Category', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Category = hexo.model('Category'); const Post = hexo.model('Post'); const PostCategory = hexo.model('PostCategory'); - const defaults = require('../../../dist/hexo/default_config'); before(() => hexo.init()); @@ -282,7 +280,7 @@ describe('Category', () => { await Promise.all(posts.map(post => post.setCategories(['foo']))); const cat = Category.findOne({name: 'foo'}); - await Category.removeById(cat._id); + await Category.removeById(cat._id!); PostCategory.find({category_id: cat._id}).should.have.lengthOf(0); diff --git a/test/scripts/models/index.js b/test/scripts/models/index.js deleted file mode 100644 index bde621745c..0000000000 --- a/test/scripts/models/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -describe('Models', () => { - require('./asset'); - require('./cache'); - require('./category'); - require('./moment'); - require('./page'); - require('./post'); - require('./post_asset'); - require('./tag'); -}); diff --git a/test/scripts/models/moment.js b/test/scripts/models/moment.ts similarity index 93% rename from test/scripts/models/moment.js rename to test/scripts/models/moment.ts index e5054575b8..19fa102b81 100644 --- a/test/scripts/models/moment.js +++ b/test/scripts/models/moment.ts @@ -1,7 +1,7 @@ -'use strict'; - -const moment = require('moment-timezone'); -const SchemaTypeMoment = require('../../../dist/models/types/moment'); +import moment from 'moment-timezone'; +import SchemaTypeMoment from '../../../lib/models/types/moment'; +import chai from 'chai'; +const should = chai.should(); describe('SchemaTypeMoment', () => { const type = new SchemaTypeMoment('test'); @@ -50,7 +50,7 @@ describe('SchemaTypeMoment', () => { it('validate() - required', () => { const type = new SchemaTypeMoment('test', {required: true}); - + // @ts-ignore should.throw(() => type.validate(), '`test` is required!'); }); @@ -99,11 +99,13 @@ describe('SchemaTypeMoment', () => { it('u$inc()', () => { type.u$inc(moment(1e8), 1).valueOf().should.eql(1e8 + 1); + // @ts-expect-error should.not.exist(undefined, 1); }); it('u$dec()', () => { type.u$dec(moment(1e8), 1).valueOf().should.eql(1e8 - 1); + // @ts-expect-error should.not.exist(undefined, 1); }); }); diff --git a/test/scripts/models/page.js b/test/scripts/models/page.ts similarity index 92% rename from test/scripts/models/page.js rename to test/scripts/models/page.ts index 8a6356861e..8e9ae60469 100644 --- a/test/scripts/models/page.js +++ b/test/scripts/models/page.ts @@ -1,13 +1,13 @@ -'use strict'; - -const { join } = require('path'); -const { deepMerge, full_url_for } = require('hexo-util'); +import { join } from 'path'; +import { deepMerge, full_url_for } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import defaults from '../../../lib/hexo/default_config'; +import chai from 'chai'; +const should = chai.should(); describe('Page', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Page = hexo.model('Page'); - const defaults = require('../../../dist/hexo/default_config'); beforeEach(() => { hexo.config = deepMerge({}, defaults); }); diff --git a/test/scripts/models/post.js b/test/scripts/models/post.ts similarity index 97% rename from test/scripts/models/post.js rename to test/scripts/models/post.ts index ded1dc66be..258d5dac6e 100644 --- a/test/scripts/models/post.js +++ b/test/scripts/models/post.ts @@ -1,11 +1,12 @@ -'use strict'; - -const { join, sep } = require('path'); -const Promise = require('bluebird'); -const { full_url_for } = require('hexo-util'); +import { join, sep } from 'path'; +// @ts-ignore +import Promise from 'bluebird'; +import { full_url_for } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('Post', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Post = hexo.model('Post'); const Tag = hexo.model('Tag'); @@ -245,7 +246,7 @@ describe('Post', () => { Tag.map(tag => tag.name).should.have.members(['foo', 'bar', 'baz']); return posts; - }).map(post => Post.removeById(post._id))); + }).map((post: any) => Post.removeById(post._id))); it('setTags() - empty tag', () => { let id; diff --git a/test/scripts/models/post_asset.js b/test/scripts/models/post_asset.ts similarity index 94% rename from test/scripts/models/post_asset.js rename to test/scripts/models/post_asset.ts index 8e6d765304..26004d6225 100644 --- a/test/scripts/models/post_asset.js +++ b/test/scripts/models/post_asset.ts @@ -1,14 +1,12 @@ -'use strict'; - -const { join } = require('path'); +import { join } from 'path'; +import Hexo from '../../../lib/hexo'; +import defaults from '../../../lib/hexo/default_config'; describe('PostAsset', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const PostAsset = hexo.model('PostAsset'); const Post = hexo.model('Post'); let post; - const defaults = require('../../../dist/hexo/default_config'); before(async () => { await hexo.init(); diff --git a/test/scripts/models/tag.js b/test/scripts/models/tag.ts similarity index 96% rename from test/scripts/models/tag.js rename to test/scripts/models/tag.ts index 7fb86124ca..94108d6521 100644 --- a/test/scripts/models/tag.js +++ b/test/scripts/models/tag.ts @@ -1,14 +1,12 @@ -'use strict'; - -const { deepMerge, full_url_for } = require('hexo-util'); +import { deepMerge, full_url_for } from 'hexo-util'; +import Hexo from '../../../lib/hexo'; +import defaults from '../../../lib/hexo/default_config'; describe('Tag', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); const Tag = hexo.model('Tag'); const Post = hexo.model('Post'); const PostTag = hexo.model('PostTag'); - const defaults = require('../../../dist/hexo/default_config'); before(() => hexo.init()); @@ -243,7 +241,7 @@ describe('Tag', () => { await Promise.all(posts.map(post => post.setTags(['foo']))); const tag = Tag.findOne({name: 'foo'}); - await Tag.removeById(tag._id); + await Tag.removeById(tag._id!); PostTag.find({tag_id: tag._id}).should.have.lengthOf(0); diff --git a/test/scripts/processors/asset.js b/test/scripts/processors/asset.ts similarity index 96% rename from test/scripts/processors/asset.js rename to test/scripts/processors/asset.ts index 2a268714c3..1e78bc44b1 100644 --- a/test/scripts/processors/asset.js +++ b/test/scripts/processors/asset.ts @@ -1,17 +1,18 @@ -'use strict'; - -const { dirname, join } = require('path'); -const { mkdirs, rmdir, stat, unlink, writeFile } = require('hexo-fs'); -const { spy } = require('sinon'); +import { dirname, join } from 'path'; +import { mkdirs, rmdir, stat, unlink, writeFile } from 'hexo-fs'; +import { spy } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import defaults from '../../../lib/hexo/default_config'; +import assets from '../../../lib/plugins/processor/asset'; +import chai from 'chai'; +const should = chai.should(); const dateFormat = 'YYYY-MM-DD HH:mm:ss'; describe('asset', () => { - const Hexo = require('../../../dist/hexo'); - const defaults = require('../../../dist/hexo/default_config'); const baseDir = join(__dirname, 'asset_test'); const hexo = new Hexo(baseDir); - const asset = require('../../../dist/plugins/processor/asset')(hexo); + const asset = assets(hexo); const process = asset.process.bind(hexo); const { pattern } = asset; const { source } = hexo; @@ -93,7 +94,7 @@ describe('asset', () => { ]); }); - it('asset - type: create (when source path is configed to parent directory)', async () => { + it('asset - type: create (when source path is configured to parent directory)', async () => { const file = newFile({ path: '../../source/foo.jpg', type: 'create', @@ -294,7 +295,7 @@ describe('asset', () => { const id = doc._id; await process(file); const page = Page.findOne({ source: file.path }); - page._id.should.eql(id); + page._id!.should.eql(id); page.title.should.eql('Hello world'); await Promise.all([ diff --git a/test/scripts/processors/common.js b/test/scripts/processors/common.js deleted file mode 100644 index 1c4a54cd50..0000000000 --- a/test/scripts/processors/common.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -const moment = require('moment'); - -describe('common', () => { - const common = require('../../../dist/plugins/processor/common'); - - it('isTmpFile()', () => { - common.isTmpFile('foo').should.be.false; - common.isTmpFile('foo%').should.be.true; - common.isTmpFile('foo~').should.be.true; - }); - - it('isHiddenFile()', () => { - common.isHiddenFile('foo').should.be.false; - common.isHiddenFile('_foo').should.be.true; - common.isHiddenFile('foo/_bar').should.be.true; - common.isHiddenFile('.foo').should.be.true; - common.isHiddenFile('foo/.bar').should.be.true; - }); - - it('ignoreTmpAndHiddenFile()', () => { - const pattern = common.ignoreTmpAndHiddenFile; - - pattern.match('foo').should.be.true; - pattern.match('foo%').should.be.false; - pattern.match('foo~').should.be.false; - pattern.match('_foo').should.be.false; - pattern.match('foo/_bar').should.be.false; - pattern.match('.foo').should.be.false; - pattern.match('foo/.bar').should.be.false; - }); - - it('toDate()', () => { - const m = moment(); - const d = new Date(); - - should.not.exist(common.toDate()); - common.toDate(m).should.eql(m); - common.toDate(d).should.eql(d); - common.toDate(1e8).should.eql(new Date(1e8)); - common.toDate('2014-04-25T01:32:21.196Z').should.eql(new Date('2014-04-25T01:32:21.196Z')); - common.toDate('Apr 24 2014').should.eql(new Date(2014, 3, 24)); - should.not.exist(common.toDate('foo')); - }); - - it('timezone() - date', () => { - const d = new Date(Date.UTC(1972, 2, 29, 0, 0, 0)); - const d_timezone_UTC = common.timezone(d, 'UTC'); - (common.timezone(d, 'Asia/Shanghai') - d_timezone_UTC).should.eql(-8 * 3600 * 1000); - (common.timezone(d, 'Asia/Bangkok') - d_timezone_UTC).should.eql(-7 * 3600 * 1000); - (common.timezone(d, 'America/Los_Angeles') - d_timezone_UTC).should.eql(8 * 3600 * 1000); - }); - - it('timezone() - moment', () => { - const d = moment(new Date(Date.UTC(1972, 2, 29, 0, 0, 0))); - const d_timezone_UTC = common.timezone(d, 'UTC'); - (common.timezone(d, 'Europe/Moscow') - d_timezone_UTC).should.eql(-3 * 3600 * 1000); - }); - - it('isMatch() - string', () => { - // String - common.isMatch('foo/test.html', 'foo/*.html').should.be.true; - common.isMatch('foo/test.html', 'bar/*.html').should.be.false; - - // Array - common.isMatch('foo/test.html', []).should.be.false; - common.isMatch('foo/test.html', ['foo/*.html']).should.be.true; - common.isMatch('foo/test.html', ['bar/*.html', 'foo/*.html']).should.be.true; - common.isMatch('foo/test.html', ['bar/*.html', 'baz/*.html']).should.be.false; - - // Undefined - common.isMatch('foo/test.html').should.be.false; - }); -}); diff --git a/test/scripts/processors/common.ts b/test/scripts/processors/common.ts new file mode 100644 index 0000000000..444b073c7f --- /dev/null +++ b/test/scripts/processors/common.ts @@ -0,0 +1,72 @@ +import moment from 'moment'; +import { isTmpFile, isHiddenFile, ignoreTmpAndHiddenFile as pattern, toDate, timezone, isMatch } from '../../../lib/plugins/processor/common'; +import chai from 'chai'; +const should = chai.should(); + +describe('common', () => { + it('isTmpFile()', () => { + isTmpFile('foo').should.be.false; + isTmpFile('foo%').should.be.true; + isTmpFile('foo~').should.be.true; + }); + + it('isHiddenFile()', () => { + isHiddenFile('foo').should.be.false; + isHiddenFile('_foo').should.be.true; + isHiddenFile('foo/_bar').should.be.true; + isHiddenFile('.foo').should.be.true; + isHiddenFile('foo/.bar').should.be.true; + }); + + it('ignoreTmpAndHiddenFile()', () => { + pattern.match('foo').should.be.true; + pattern.match('foo%').should.be.false; + pattern.match('foo~').should.be.false; + pattern.match('_foo').should.be.false; + pattern.match('foo/_bar').should.be.false; + pattern.match('.foo').should.be.false; + pattern.match('foo/.bar').should.be.false; + }); + + it('toDate()', () => { + const m = moment(); + const d = new Date(); + + should.not.exist(toDate()); + toDate(m).should.eql(m); + toDate(d).should.eql(d); + toDate(1e8).should.eql(new Date(1e8)); + toDate('2014-04-25T01:32:21.196Z').should.eql(new Date('2014-04-25T01:32:21.196Z')); + toDate('Apr 24 2014').should.eql(new Date(2014, 3, 24)); + should.not.exist(toDate('foo')); + }); + + it('timezone() - date', () => { + const d = new Date(Date.UTC(1972, 2, 29, 0, 0, 0)); + const d_timezone_UTC = timezone(d, 'UTC').getTime(); + (timezone(d, 'Asia/Shanghai').getTime() - d_timezone_UTC).should.eql(-8 * 3600 * 1000); + (timezone(d, 'Asia/Bangkok').getTime() - d_timezone_UTC).should.eql(-7 * 3600 * 1000); + (timezone(d, 'America/Los_Angeles').getTime() - d_timezone_UTC).should.eql(8 * 3600 * 1000); + }); + + it('timezone() - moment', () => { + const d = moment(new Date(Date.UTC(1972, 2, 29, 0, 0, 0))); + const d_timezone_UTC = timezone(d, 'UTC').getTime(); + (timezone(d, 'Europe/Moscow').getTime() - d_timezone_UTC).should.eql(-3 * 3600 * 1000); + }); + + it('isMatch() - string', () => { + // String + isMatch('foo/test.html', 'foo/*.html').should.be.true; + isMatch('foo/test.html', 'bar/*.html').should.be.false; + + // Array + isMatch('foo/test.html', []).should.be.false; + isMatch('foo/test.html', ['foo/*.html']).should.be.true; + isMatch('foo/test.html', ['bar/*.html', 'foo/*.html']).should.be.true; + isMatch('foo/test.html', ['bar/*.html', 'baz/*.html']).should.be.false; + + // Undefined + isMatch('foo/test.html').should.be.false; + }); +}); diff --git a/test/scripts/processors/data.js b/test/scripts/processors/data.ts similarity index 91% rename from test/scripts/processors/data.js rename to test/scripts/processors/data.ts index ef5493e469..95687afce9 100644 --- a/test/scripts/processors/data.js +++ b/test/scripts/processors/data.ts @@ -1,14 +1,16 @@ -'use strict'; - -const Promise = require('bluebird'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const { join } = require('path'); +// @ts-ignore +import Promise from 'bluebird'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +import { join } from 'path'; +import Hexo from '../../../lib/hexo'; +import data from '../../../lib/plugins/processor/data'; +import chai from 'chai'; +const should = chai.should(); describe('data', () => { - const Hexo = require('../../../dist/hexo'); const baseDir = join(__dirname, 'data_test'); const hexo = new Hexo(baseDir); - const processor = require('../../../dist/plugins/processor/data')(hexo); + const processor = data(hexo); const process = Promise.method(processor.process).bind(hexo); const { source } = hexo; const { File } = source; diff --git a/test/scripts/processors/index.js b/test/scripts/processors/index.js deleted file mode 100644 index 33e12195f0..0000000000 --- a/test/scripts/processors/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -describe('Processors', () => { - require('./asset'); - require('./common'); - require('./data'); - require('./post'); -}); diff --git a/test/scripts/processors/post.js b/test/scripts/processors/post.ts similarity index 97% rename from test/scripts/processors/post.js rename to test/scripts/processors/post.ts index fea2563d62..3bc59bba80 100644 --- a/test/scripts/processors/post.js +++ b/test/scripts/processors/post.ts @@ -1,18 +1,23 @@ -'use strict'; -const { join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); -const defaultConfig = require('../../../dist/hexo/default_config'); +import { join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import defaultConfig from '../../../lib/hexo/default_config'; +import Hexo from '../../../lib/hexo'; +import posts from '../../../lib/plugins/processor/post'; +import chai from 'chai'; +const should = chai.should(); +type PostParams = Parameters['process']> +type PostReturn = ReturnType['process']> const dateFormat = 'YYYY-MM-DD HH:mm:ss'; describe('post', () => { - const Hexo = require('../../../dist/hexo'); const baseDir = join(__dirname, 'post_test'); const hexo = new Hexo(baseDir); - const post = require('../../../dist/plugins/processor/post')(hexo); - const process = Promise.method(post.process.bind(hexo)); + const post = posts(hexo); + const process: (...args: PostParams) => Promise = Promise.method(post.process.bind(hexo)); const { pattern } = post; const { source } = hexo; const { File } = source; @@ -374,7 +379,7 @@ describe('post', () => { await process(file); const post = Post.findOne({ source: file.path }); - post._id.should.eql(id); + post._id!.should.eql(id); post.title.should.eql('New world'); return Promise.all([ @@ -1294,7 +1299,7 @@ describe('post', () => { it('asset - post - skip render', async () => { hexo.config.post_asset_folder = true; - hexo.config.skip_render = '**.yml'; + hexo.config.skip_render = '**.yml' as any; const file = newFile({ path: 'foo.md', @@ -1319,7 +1324,7 @@ describe('post', () => { PostAsset.findById(id).renderable.should.be.false; hexo.config.post_asset_folder = false; - hexo.config.skip_render = ''; + hexo.config.skip_render = '' as any; return Promise.all([ unlink(file.source), diff --git a/test/scripts/renderers/index.js b/test/scripts/renderers/index.js deleted file mode 100644 index 30808e80a1..0000000000 --- a/test/scripts/renderers/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -describe('Renderers', () => { - require('./json'); - require('./plain'); - require('./yaml'); - require('./nunjucks'); -}); diff --git a/test/scripts/renderers/json.js b/test/scripts/renderers/json.ts similarity index 71% rename from test/scripts/renderers/json.js rename to test/scripts/renderers/json.ts index bdcf516a21..9971dd4970 100644 --- a/test/scripts/renderers/json.js +++ b/test/scripts/renderers/json.ts @@ -1,8 +1,6 @@ -'use strict'; +import r from '../../../lib/plugins/renderer/json'; describe('json', () => { - const r = require('../../../dist/plugins/renderer/json'); - it('normal', () => { const data = { foo: 1, diff --git a/test/scripts/renderers/nunjucks.js b/test/scripts/renderers/nunjucks.ts similarity index 96% rename from test/scripts/renderers/nunjucks.js rename to test/scripts/renderers/nunjucks.ts index 4159f424b0..5b217a7bae 100644 --- a/test/scripts/renderers/nunjucks.js +++ b/test/scripts/renderers/nunjucks.ts @@ -1,8 +1,8 @@ -'use strict'; +import r from '../../../lib/plugins/renderer/nunjucks'; +import { dirname, join } from 'path'; +import chai from 'chai'; +const should = chai.should(); -require('chai').should(); -const r = require('../../../dist/plugins/renderer/nunjucks'); -const { dirname, join } = require('path'); describe('nunjucks', () => { const fixturePath = join(dirname(dirname(__dirname)), 'fixtures', 'hello.njk'); diff --git a/test/scripts/renderers/plain.js b/test/scripts/renderers/plain.ts similarity index 56% rename from test/scripts/renderers/plain.js rename to test/scripts/renderers/plain.ts index 24982baa14..ec5d6bf05d 100644 --- a/test/scripts/renderers/plain.js +++ b/test/scripts/renderers/plain.ts @@ -1,8 +1,6 @@ -'use strict'; +import r from '../../../lib/plugins/renderer/plain'; describe('plain', () => { - const r = require('../../../dist/plugins/renderer/plain'); - it('normal', () => { r({text: '123'}).should.eql('123'); }); diff --git a/test/scripts/renderers/yaml.js b/test/scripts/renderers/yaml.ts similarity index 80% rename from test/scripts/renderers/yaml.js rename to test/scripts/renderers/yaml.ts index bf26b6fde0..2cd7934cf9 100644 --- a/test/scripts/renderers/yaml.js +++ b/test/scripts/renderers/yaml.ts @@ -1,8 +1,6 @@ -'use strict'; +import r from '../../../lib/plugins/renderer/yaml'; describe('yaml', () => { - const r = require('../../../dist/plugins/renderer/yaml'); - it('normal', () => { r({text: 'foo: 1'}).should.eql({foo: 1}); }); diff --git a/test/scripts/tags/asset_img.js b/test/scripts/tags/asset_img.ts similarity index 89% rename from test/scripts/tags/asset_img.js rename to test/scripts/tags/asset_img.ts index 3fa8817087..78e841b1d2 100644 --- a/test/scripts/tags/asset_img.js +++ b/test/scripts/tags/asset_img.ts @@ -1,11 +1,13 @@ -'use strict'; - -const Promise = require('bluebird'); +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import tagAssetImg from '../../../lib/plugins/tag/asset_img'; +import chai from 'chai'; +const should = chai.should(); describe('asset_img', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const assetImgTag = require('../../../dist/plugins/tag/asset_img')(hexo); + const assetImgTag = tagAssetImg(hexo); const Post = hexo.model('Post'); const PostAsset = hexo.model('PostAsset'); let post; diff --git a/test/scripts/tags/asset_link.js b/test/scripts/tags/asset_link.ts similarity index 89% rename from test/scripts/tags/asset_link.js rename to test/scripts/tags/asset_link.ts index a75c8effba..d03ec1fdb9 100644 --- a/test/scripts/tags/asset_link.js +++ b/test/scripts/tags/asset_link.ts @@ -1,11 +1,13 @@ -'use strict'; - -const Promise = require('bluebird'); +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import tagAssetLink from '../../../lib/plugins/tag/asset_link'; +import chai from 'chai'; +const should = chai.should(); describe('asset_link', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const assetLinkTag = require('../../../dist/plugins/tag/asset_link')(hexo); + const assetLinkTag = tagAssetLink(hexo); const Post = hexo.model('Post'); const PostAsset = hexo.model('PostAsset'); let post; diff --git a/test/scripts/tags/asset_path.js b/test/scripts/tags/asset_path.ts similarity index 83% rename from test/scripts/tags/asset_path.js rename to test/scripts/tags/asset_path.ts index 281a015232..ad84a5ff11 100644 --- a/test/scripts/tags/asset_path.js +++ b/test/scripts/tags/asset_path.ts @@ -1,11 +1,13 @@ -'use strict'; - -const Promise = require('bluebird'); +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import tagAssetPath from '../../../lib/plugins/tag/asset_path'; +import chai from 'chai'; +const should = chai.should(); describe('asset_path', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const assetPathTag = require('../../../dist/plugins/tag/asset_path')(hexo); + const assetPathTag = tagAssetPath(hexo); const Post = hexo.model('Post'); const PostAsset = hexo.model('PostAsset'); let post; diff --git a/test/scripts/tags/blockquote.js b/test/scripts/tags/blockquote.ts similarity index 87% rename from test/scripts/tags/blockquote.js rename to test/scripts/tags/blockquote.ts index d1b1661557..8fa575c55a 100644 --- a/test/scripts/tags/blockquote.js +++ b/test/scripts/tags/blockquote.ts @@ -1,13 +1,13 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import tagBlockquote from '../../../lib/plugins/tag/blockquote'; describe('blockquote', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const blockquote = require('../../../dist/plugins/tag/blockquote')(hexo); + const blockquote = tagBlockquote(hexo); before(() => hexo.init().then(() => hexo.loadPlugin(require.resolve('hexo-renderer-marked')))); - const bq = (args, content) => blockquote(args.split(' '), content || ''); + const bq = (args, content?) => blockquote(args.split(' '), content || ''); it('default', () => { const result = bq('', '123456 **bold** and *italic*'); diff --git a/test/scripts/tags/code.js b/test/scripts/tags/code.ts similarity index 94% rename from test/scripts/tags/code.js rename to test/scripts/tags/code.ts index a9c2d5c966..2b314c9307 100644 --- a/test/scripts/tags/code.js +++ b/test/scripts/tags/code.ts @@ -1,14 +1,12 @@ -'use strict'; - -const util = require('hexo-util'); -const cheerio = require('cheerio'); +import { escapeHTML, highlight as utilHighlight, prismHighlight } from 'hexo-util'; +import cheerio from 'cheerio'; +import Hexo from '../../../lib/hexo'; +import tagCode from '../../../lib/plugins/tag/code'; describe('code', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(); - require('../../../dist/plugins/highlight/')(hexo); - const codeTag = require('../../../dist/plugins/tag/code')(hexo); - const { escapeHTML } = util; + require('../../../lib/plugins/highlight/')(hexo); + const codeTag = tagCode(hexo); const fixture = [ 'if (tired && night){', @@ -20,14 +18,14 @@ describe('code', () => { return codeTag(args.split(' '), content); } - function highlight(code, options) { - return util.highlight(code, options || {}) + function highlight(code, options?) { + return utilHighlight(code, options || {}) .replace(/{/g, '{') .replace(/}/g, '}'); } - function prism(code, options) { - return util.prismHighlight(code, options || {}) + function prism(code, options?) { + return prismHighlight(code, options || {}) .replace(/{/g, '{') .replace(/}/g, '}'); } diff --git a/test/scripts/tags/full_url_for.js b/test/scripts/tags/full_url_for.js deleted file mode 100644 index ea01912392..0000000000 --- a/test/scripts/tags/full_url_for.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const cheerio = require('cheerio'); - -describe('full_url_for', () => { - const ctx = { - config: { url: 'https://example.com' } - }; - - const fullUrlForTag = require('../../../dist/plugins/tag/full_url_for')(ctx); - const fullUrlFor = args => fullUrlForTag(args.split(' ')); - - it('no path input', () => { - const $ = cheerio.load(fullUrlFor('nopath')); - $('a').attr('href').should.eql(ctx.config.url + '/'); - $('a').html().should.eql('nopath'); - }); - - it('internal url', () => { - let $ = cheerio.load(fullUrlFor('index index.html')); - $('a').attr('href').should.eql(ctx.config.url + '/index.html'); - $('a').html().should.eql('index'); - - $ = cheerio.load(fullUrlFor('index /')); - $('a').attr('href').should.eql(ctx.config.url + '/'); - $('a').html().should.eql('index'); - - $ = cheerio.load(fullUrlFor('index /index.html')); - $('a').attr('href').should.eql(ctx.config.url + '/index.html'); - $('a').html().should.eql('index'); - }); - - it('internel url (pretty_urls.trailing_index disabled)', () => { - ctx.config.pretty_urls = { trailing_index: false }; - let $ = cheerio.load(fullUrlFor('index index.html')); - $('a').attr('href').should.eql(ctx.config.url + '/'); - $('a').html().should.eql('index'); - - $ = cheerio.load(fullUrlFor('index /index.html')); - $('a').attr('href').should.eql(ctx.config.url + '/'); - $('a').html().should.eql('index'); - }); - - it('external url', () => { - [ - 'https://hexo.io/', - '//google.com/', - // 'index.html' in external link should not be removed - '//google.com/index.html' - ].forEach(url => { - const $ = cheerio.load(fullUrlFor(`external ${url}`)); - $('a').attr('href').should.eql(url); - $('a').html().should.eql('external'); - }); - }); - - it('only hash', () => { - const $ = cheerio.load(fullUrlFor('hash #test')); - $('a').attr('href').should.eql(ctx.config.url + '/#test'); - $('a').html().should.eql('hash'); - }); -}); diff --git a/test/scripts/tags/full_url_for.ts b/test/scripts/tags/full_url_for.ts new file mode 100644 index 0000000000..d7a64b0e0b --- /dev/null +++ b/test/scripts/tags/full_url_for.ts @@ -0,0 +1,61 @@ +import cheerio from 'cheerio'; +import tagFullUrlFor from '../../../lib/plugins/tag/full_url_for'; + +describe('full_url_for', () => { + const ctx: any = { + config: { url: 'https://example.com' } + }; + + const fullUrlForTag = tagFullUrlFor(ctx); + const fullUrlFor = args => fullUrlForTag(args.split(' ')); + + it('no path input', () => { + const $ = cheerio.load(fullUrlFor('nopath')); + $('a').attr('href')!.should.eql(ctx.config.url + '/'); + $('a').html()!.should.eql('nopath'); + }); + + it('internal url', () => { + let $ = cheerio.load(fullUrlFor('index index.html')); + $('a').attr('href')!.should.eql(ctx.config.url + '/index.html'); + $('a').html()!.should.eql('index'); + + $ = cheerio.load(fullUrlFor('index /')); + $('a').attr('href')!.should.eql(ctx.config.url + '/'); + $('a').html()!.should.eql('index'); + + $ = cheerio.load(fullUrlFor('index /index.html')); + $('a').attr('href')!.should.eql(ctx.config.url + '/index.html'); + $('a').html()!.should.eql('index'); + }); + + it('internal url (pretty_urls.trailing_index disabled)', () => { + ctx.config.pretty_urls = { trailing_index: false }; + let $ = cheerio.load(fullUrlFor('index index.html')); + $('a').attr('href')!.should.eql(ctx.config.url + '/'); + $('a').html()!.should.eql('index'); + + $ = cheerio.load(fullUrlFor('index /index.html')); + $('a').attr('href')!.should.eql(ctx.config.url + '/'); + $('a').html()!.should.eql('index'); + }); + + it('external url', () => { + [ + 'https://hexo.io/', + '//google.com/', + // 'index.html' in external link should not be removed + '//google.com/index.html' + ].forEach(url => { + const $ = cheerio.load(fullUrlFor(`external ${url}`)); + $('a').attr('href')!.should.eql(url); + $('a').html()!.should.eql('external'); + }); + }); + + it('only hash', () => { + const $ = cheerio.load(fullUrlFor('hash #test')); + $('a').attr('href')!.should.eql(ctx.config.url + '/#test'); + $('a').html()!.should.eql('hash'); + }); +}); diff --git a/test/scripts/tags/iframe.js b/test/scripts/tags/iframe.js deleted file mode 100644 index 8f07063ccb..0000000000 --- a/test/scripts/tags/iframe.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const cheerio = require('cheerio'); - -describe('iframe', () => { - const iframe = require('../../../dist/plugins/tag/iframe'); - - it('url', () => { - const $ = cheerio.load(iframe(['https://zespia.tw'])); - - $('iframe').attr('src').should.eql('https://zespia.tw/'); - $('iframe').attr('width').should.eql('100%'); - $('iframe').attr('height').should.eql('300'); - $('iframe').attr('frameborder').should.eql('0'); - $('iframe').attr('allowfullscreen').should.eql(''); - $('iframe').attr('loading').should.eql('lazy'); - }); - - it('width', () => { - const $ = cheerio.load(iframe(['https://zespia.tw', '500'])); - - $('iframe').attr('src').should.eql('https://zespia.tw/'); - $('iframe').attr('width').should.eql('500'); - $('iframe').attr('height').should.eql('300'); - $('iframe').attr('frameborder').should.eql('0'); - $('iframe').attr('allowfullscreen').should.eql(''); - $('iframe').attr('loading').should.eql('lazy'); - }); - - it('height', () => { - const $ = cheerio.load(iframe(['https://zespia.tw', '500', '600'])); - - $('iframe').attr('src').should.eql('https://zespia.tw/'); - $('iframe').attr('width').should.eql('500'); - $('iframe').attr('height').should.eql('600'); - $('iframe').attr('frameborder').should.eql('0'); - $('iframe').attr('allowfullscreen').should.eql(''); - $('iframe').attr('loading').should.eql('lazy'); - }); -}); diff --git a/test/scripts/tags/iframe.ts b/test/scripts/tags/iframe.ts new file mode 100644 index 0000000000..7f835f86cd --- /dev/null +++ b/test/scripts/tags/iframe.ts @@ -0,0 +1,37 @@ +import cheerio from 'cheerio'; +import iframe from '../../../lib/plugins/tag/iframe'; + +describe('iframe', () => { + it('url', () => { + const $ = cheerio.load(iframe(['https://zespia.tw'])); + + $('iframe').attr('src')!.should.eql('https://zespia.tw/'); + $('iframe').attr('width')!.should.eql('100%'); + $('iframe').attr('height')!.should.eql('300'); + $('iframe').attr('frameborder')!.should.eql('0'); + $('iframe').attr('allowfullscreen')!.should.eql(''); + $('iframe').attr('loading')!.should.eql('lazy'); + }); + + it('width', () => { + const $ = cheerio.load(iframe(['https://zespia.tw', '500'])); + + $('iframe').attr('src')!.should.eql('https://zespia.tw/'); + $('iframe').attr('width')!.should.eql('500'); + $('iframe').attr('height')!.should.eql('300'); + $('iframe').attr('frameborder')!.should.eql('0'); + $('iframe').attr('allowfullscreen')!.should.eql(''); + $('iframe').attr('loading')!.should.eql('lazy'); + }); + + it('height', () => { + const $ = cheerio.load(iframe(['https://zespia.tw', '500', '600'])); + + $('iframe').attr('src')!.should.eql('https://zespia.tw/'); + $('iframe').attr('width')!.should.eql('500'); + $('iframe').attr('height')!.should.eql('600'); + $('iframe').attr('frameborder')!.should.eql('0'); + $('iframe').attr('allowfullscreen')!.should.eql(''); + $('iframe').attr('loading')!.should.eql('lazy'); + }); +}); diff --git a/test/scripts/tags/img.js b/test/scripts/tags/img.js deleted file mode 100644 index 10cd72f549..0000000000 --- a/test/scripts/tags/img.js +++ /dev/null @@ -1,152 +0,0 @@ -'use strict'; - -const pathFn = require('path'); -const cheerio = require('cheerio'); - -describe('img', () => { - const Hexo = require('../../../dist/hexo'); - const hexo = new Hexo(pathFn.join(__dirname, 'img_test')); - const img = require('../../../dist/plugins/tag/img')(hexo); - - before(() => hexo.init()); - - it('src', () => { - const $ = cheerio.load(img(['https://placekitten.com/200/300'])); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - }); - - it('src //', () => { - const $ = cheerio.load(img(['//placekitten.com/200/300'])); - - $('img').attr('src').should.eql('//placekitten.com/200/300'); - }); - - it('internal src', () => { - hexo.config.root = '/'; - let $ = cheerio.load(img(['/images/test.jpg'])); - $('img').attr('src').should.eql('/images/test.jpg'); - - hexo.config.url = 'http://example.com/root'; - hexo.config.root = '/root/'; - $ = cheerio.load(img(['/images/test.jpg'])); - $('img').attr('src').should.eql('/root/images/test.jpg'); - }); - - it('class + src', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - }); - - it('class + internal src', () => { - hexo.config.root = '/'; - let $ = cheerio.load(img('left /images/test.jpg'.split(' '))); - $('img').attr('src').should.eql('/images/test.jpg'); - $('img').attr('class').should.eql('left'); - - hexo.config.url = 'http://example.com/root'; - hexo.config.root = '/root/'; - $ = cheerio.load(img('left /images/test.jpg'.split(' '))); - $('img').attr('src').should.eql('/root/images/test.jpg'); - $('img').attr('class').should.eql('left'); - }); - - it('multiple classes + src', () => { - const $ = cheerio.load(img('left top https://placekitten.com/200/300'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left top'); - }); - - it('multiple classes + internal src', () => { - hexo.config.root = '/'; - let $ = cheerio.load(img('left top /images/test.jpg'.split(' '))); - $('img').attr('src').should.eql('/images/test.jpg'); - $('img').attr('class').should.eql('left top'); - - hexo.config.url = 'http://example.com/root'; - hexo.config.root = '/root/'; - $ = cheerio.load(img('left top /images/test.jpg'.split(' '))); - $('img').attr('src').should.eql('/root/images/test.jpg'); - $('img').attr('class').should.eql('left top'); - }); - - it('class + src + width', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - }); - - it('class + src + width + height', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - $('img').attr('height').should.eql('300'); - }); - - it('class + src + title', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 Place Kitten'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('title').should.eql('Place Kitten'); - }); - - it('class + src + width + title', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200 Place Kitten'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - $('img').attr('title').should.eql('Place Kitten'); - }); - - it('class + src + width + height + title', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 Place Kitten'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - $('img').attr('height').should.eql('300'); - $('img').attr('title').should.eql('Place Kitten'); - }); - - it('class + src + width + height + title + alt', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" "A cute kitten"'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - $('img').attr('height').should.eql('300'); - $('img').attr('title').should.eql('Place Kitten'); - $('img').attr('alt').should.eql('A cute kitten'); - }); - - it('single quote in double quote', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" "A \'cute\' kitten"'.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - $('img').attr('height').should.eql('300'); - $('img').attr('title').should.eql('Place Kitten'); - $('img').attr('alt').should.eql('A \'cute\' kitten'); - }); - - it('double quote in single quote', () => { - const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" \'A "cute" kitten\''.split(' '))); - - $('img').attr('src').should.eql('https://placekitten.com/200/300'); - $('img').attr('class').should.eql('left'); - $('img').attr('width').should.eql('200'); - $('img').attr('height').should.eql('300'); - $('img').attr('title').should.eql('Place Kitten'); - $('img').attr('alt').should.eql('A "cute" kitten'); - }); -}); diff --git a/test/scripts/tags/img.ts b/test/scripts/tags/img.ts new file mode 100644 index 0000000000..a4fe0592aa --- /dev/null +++ b/test/scripts/tags/img.ts @@ -0,0 +1,152 @@ +import cheerio from 'cheerio'; +import pathFn from 'path'; +import Hexo from '../../../lib/hexo'; +import tagImg from '../../../lib/plugins/tag/img'; + + +describe('img', () => { + const hexo = new Hexo(pathFn.join(__dirname, 'img_test')); + const img = tagImg(hexo); + + before(() => hexo.init()); + + it('src', () => { + const $ = cheerio.load(img(['https://placekitten.com/200/300'])); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + }); + + it('src //', () => { + const $ = cheerio.load(img(['//placekitten.com/200/300'])); + + $('img').attr('src')!.should.eql('//placekitten.com/200/300'); + }); + + it('internal src', () => { + hexo.config.root = '/'; + let $ = cheerio.load(img(['/images/test.jpg'])); + $('img').attr('src')!.should.eql('/images/test.jpg'); + + hexo.config.url = 'http://example.com/root'; + hexo.config.root = '/root/'; + $ = cheerio.load(img(['/images/test.jpg'])); + $('img').attr('src')!.should.eql('/root/images/test.jpg'); + }); + + it('class + src', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + }); + + it('class + internal src', () => { + hexo.config.root = '/'; + let $ = cheerio.load(img('left /images/test.jpg'.split(' '))); + $('img').attr('src')!.should.eql('/images/test.jpg'); + $('img').attr('class')!.should.eql('left'); + + hexo.config.url = 'http://example.com/root'; + hexo.config.root = '/root/'; + $ = cheerio.load(img('left /images/test.jpg'.split(' '))); + $('img').attr('src')!.should.eql('/root/images/test.jpg'); + $('img').attr('class')!.should.eql('left'); + }); + + it('multiple classes + src', () => { + const $ = cheerio.load(img('left top https://placekitten.com/200/300'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left top'); + }); + + it('multiple classes + internal src', () => { + hexo.config.root = '/'; + let $ = cheerio.load(img('left top /images/test.jpg'.split(' '))); + $('img').attr('src')!.should.eql('/images/test.jpg'); + $('img').attr('class')!.should.eql('left top'); + + hexo.config.url = 'http://example.com/root'; + hexo.config.root = '/root/'; + $ = cheerio.load(img('left top /images/test.jpg'.split(' '))); + $('img').attr('src')!.should.eql('/root/images/test.jpg'); + $('img').attr('class')!.should.eql('left top'); + }); + + it('class + src + width', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + }); + + it('class + src + width + height', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + $('img').attr('height')!.should.eql('300'); + }); + + it('class + src + title', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 Place Kitten'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('title')!.should.eql('Place Kitten'); + }); + + it('class + src + width + title', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200 Place Kitten'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + $('img').attr('title')!.should.eql('Place Kitten'); + }); + + it('class + src + width + height + title', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 Place Kitten'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + $('img').attr('height')!.should.eql('300'); + $('img').attr('title')!.should.eql('Place Kitten'); + }); + + it('class + src + width + height + title + alt', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" "A cute kitten"'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + $('img').attr('height')!.should.eql('300'); + $('img').attr('title')!.should.eql('Place Kitten'); + $('img').attr('alt')!.should.eql('A cute kitten'); + }); + + it('single quote in double quote', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" "A \'cute\' kitten"'.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + $('img').attr('height')!.should.eql('300'); + $('img').attr('title')!.should.eql('Place Kitten'); + $('img').attr('alt')!.should.eql('A \'cute\' kitten'); + }); + + it('double quote in single quote', () => { + const $ = cheerio.load(img('left https://placekitten.com/200/300 200 300 "Place Kitten" \'A "cute" kitten\''.split(' '))); + + $('img').attr('src')!.should.eql('https://placekitten.com/200/300'); + $('img').attr('class')!.should.eql('left'); + $('img').attr('width')!.should.eql('200'); + $('img').attr('height')!.should.eql('300'); + $('img').attr('title')!.should.eql('Place Kitten'); + $('img').attr('alt')!.should.eql('A "cute" kitten'); + }); +}); diff --git a/test/scripts/tags/include_code.js b/test/scripts/tags/include_code.ts similarity index 93% rename from test/scripts/tags/include_code.js rename to test/scripts/tags/include_code.ts index 3c18068609..fa23a993f1 100644 --- a/test/scripts/tags/include_code.js +++ b/test/scripts/tags/include_code.ts @@ -1,15 +1,17 @@ -'use strict'; - -const { join } = require('path'); -const { rmdir, writeFile } = require('hexo-fs'); -const { highlight, prismHighlight } = require('hexo-util'); -const Promise = require('bluebird'); +import { join } from 'path'; +import { rmdir, writeFile } from 'hexo-fs'; +import { highlight, prismHighlight } from 'hexo-util'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import tagIncludeCode from '../../../lib/plugins/tag/include_code'; +import chai from 'chai'; +const should = chai.should(); describe('include_code', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'include_code_test')); - require('../../../dist/plugins/highlight/')(hexo); - const includeCode = Promise.method(require('../../../dist/plugins/tag/include_code')(hexo)); + require('../../../lib/plugins/highlight/')(hexo); + const includeCode = Promise.method(tagIncludeCode(hexo)); const path = join(hexo.source_dir, hexo.config.code_dir, 'test.js'); const defaultCfg = JSON.parse(JSON.stringify(hexo.config)); diff --git a/test/scripts/tags/index.js b/test/scripts/tags/index.js deleted file mode 100644 index 21dc58a9b3..0000000000 --- a/test/scripts/tags/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -describe('Tags', () => { - require('./asset_img'); - require('./asset_link'); - require('./asset_path'); - require('./blockquote'); - require('./code'); - require('./full_url_for'); - require('./iframe'); - require('./img'); - require('./include_code'); - require('./link'); - require('./post_link'); - require('./post_path'); - require('./pullquote'); - require('./url_for'); -}); diff --git a/test/scripts/tags/link.js b/test/scripts/tags/link.js deleted file mode 100644 index 4adcdcf0cb..0000000000 --- a/test/scripts/tags/link.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const cheerio = require('cheerio'); - -describe('link', () => { - const link = require('../../../dist/plugins/tag/link'); - - it('text + url', () => { - const $ = cheerio.load(link('Click here to Google https://google.com'.split(' '))); - - $('a').attr('href').should.eql('https://google.com/'); - $('a').html().should.eql('Click here to Google'); - }); - - it('text + url + external', () => { - let $ = cheerio.load(link('Click here to Google https://google.com true'.split(' '))); - - $('a').attr('href').should.eql('https://google.com/'); - $('a').html().should.eql('Click here to Google'); - $('a').attr('target').should.eql('_blank'); - - $ = cheerio.load(link('Click here to Google https://google.com false'.split(' '))); - - $('a').attr('href').should.eql('https://google.com/'); - $('a').html().should.eql('Click here to Google'); - $('a').attr('title').should.eql(''); - $('a').attr('target').should.eql(''); - }); - - it('text + url + title', () => { - const $ = cheerio.load(link('Click here to Google https://google.com Google link'.split(' '))); - - $('a').attr('href').should.eql('https://google.com/'); - $('a').html().should.eql('Click here to Google'); - $('a').attr('title').should.eql('Google link'); - }); - - it('text + url + external + title', () => { - let $ = cheerio.load(link('Click here to Google https://google.com true Google link'.split(' '))); - - $('a').attr('href').should.eql('https://google.com/'); - $('a').html().should.eql('Click here to Google'); - $('a').attr('target').should.eql('_blank'); - $('a').attr('title').should.eql('Google link'); - - $ = cheerio.load(link('Click here to Google https://google.com false Google link'.split(' '))); - - $('a').attr('href').should.eql('https://google.com/'); - $('a').html().should.eql('Click here to Google'); - $('a').attr('target').should.eql(''); - $('a').attr('title').should.eql('Google link'); - }); -}); diff --git a/test/scripts/tags/link.ts b/test/scripts/tags/link.ts new file mode 100644 index 0000000000..b421af6c8e --- /dev/null +++ b/test/scripts/tags/link.ts @@ -0,0 +1,50 @@ +import cheerio from 'cheerio'; +import link from '../../../lib/plugins/tag/link'; + +describe('link', () => { + it('text + url', () => { + const $ = cheerio.load(link('Click here to Google https://google.com'.split(' '))); + + $('a').attr('href')!.should.eql('https://google.com/'); + $('a').html()!.should.eql('Click here to Google'); + }); + + it('text + url + external', () => { + let $ = cheerio.load(link('Click here to Google https://google.com true'.split(' '))); + + $('a').attr('href')!.should.eql('https://google.com/'); + $('a').html()!.should.eql('Click here to Google'); + $('a').attr('target')!.should.eql('_blank'); + + $ = cheerio.load(link('Click here to Google https://google.com false'.split(' '))); + + $('a').attr('href')!.should.eql('https://google.com/'); + $('a').html()!.should.eql('Click here to Google'); + $('a').attr('title')!.should.eql(''); + $('a').attr('target')!.should.eql(''); + }); + + it('text + url + title', () => { + const $ = cheerio.load(link('Click here to Google https://google.com Google link'.split(' '))); + + $('a').attr('href')!.should.eql('https://google.com/'); + $('a').html()!.should.eql('Click here to Google'); + $('a').attr('title')!.should.eql('Google link'); + }); + + it('text + url + external + title', () => { + let $ = cheerio.load(link('Click here to Google https://google.com true Google link'.split(' '))); + + $('a').attr('href')!.should.eql('https://google.com/'); + $('a').html()!.should.eql('Click here to Google'); + $('a').attr('target')!.should.eql('_blank'); + $('a').attr('title')!.should.eql('Google link'); + + $ = cheerio.load(link('Click here to Google https://google.com false Google link'.split(' '))); + + $('a').attr('href')!.should.eql('https://google.com/'); + $('a').html()!.should.eql('Click here to Google'); + $('a').attr('target')!.should.eql(''); + $('a').attr('title')!.should.eql('Google link'); + }); +}); diff --git a/test/scripts/tags/post_link.js b/test/scripts/tags/post_link.ts similarity index 87% rename from test/scripts/tags/post_link.js rename to test/scripts/tags/post_link.ts index 05839a8098..c2e990d007 100644 --- a/test/scripts/tags/post_link.js +++ b/test/scripts/tags/post_link.ts @@ -1,9 +1,11 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import tagPostLink from '../../../lib/plugins/tag/post_link'; +import chai from 'chai'; +const should = chai.should(); describe('post_link', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const postLink = require('../../../dist/plugins/tag/post_link')(hexo); + const postLink = tagPostLink(hexo); const Post = hexo.model('Post'); hexo.config.permalink = ':title/'; @@ -77,4 +79,9 @@ describe('post_link', () => { it('should keep hash', () => { postLink(['foo#bar']).should.eql('Hello world'); }); + + it('should keep subdir', () => { + hexo.config.url = 'http://example.com/subdir'; + postLink(['foo']).should.eql('Hello world'); + }); }); diff --git a/test/scripts/tags/post_path.js b/test/scripts/tags/post_path.ts similarity index 75% rename from test/scripts/tags/post_path.js rename to test/scripts/tags/post_path.ts index 5a00ecbf66..5786236d42 100644 --- a/test/scripts/tags/post_path.js +++ b/test/scripts/tags/post_path.ts @@ -1,9 +1,11 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import tagPostPath from '../../../lib/plugins/tag/post_path'; +import chai from 'chai'; +const should = chai.should(); describe('post_path', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const postPath = require('../../../dist/plugins/tag/post_path')(hexo); + const postPath = tagPostPath(hexo); const Post = hexo.model('Post'); hexo.config.permalink = ':title/'; diff --git a/test/scripts/tags/pullquote.js b/test/scripts/tags/pullquote.ts similarity index 79% rename from test/scripts/tags/pullquote.js rename to test/scripts/tags/pullquote.ts index 983f2a4a73..261f773612 100644 --- a/test/scripts/tags/pullquote.js +++ b/test/scripts/tags/pullquote.ts @@ -1,9 +1,9 @@ -'use strict'; +import Hexo from '../../../lib/hexo'; +import tagPullquote from '../../../lib/plugins/tag/pullquote'; describe('pullquote', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(__dirname); - const pullquote = require('../../../dist/plugins/tag/pullquote')(hexo); + const pullquote = tagPullquote(hexo); before(() => hexo.init().then(() => hexo.loadPlugin(require.resolve('hexo-renderer-marked')))); diff --git a/test/scripts/tags/url_for.js b/test/scripts/tags/url_for.ts similarity index 52% rename from test/scripts/tags/url_for.js rename to test/scripts/tags/url_for.ts index 1b905df59a..bb86024267 100644 --- a/test/scripts/tags/url_for.js +++ b/test/scripts/tags/url_for.ts @@ -1,53 +1,52 @@ -'use strict'; - -const cheerio = require('cheerio'); +import cheerio from 'cheerio'; +import tagUrlFor from '../../../lib/plugins/tag/url_for'; describe('url_for', () => { - const ctx = { + const ctx: any = { config: { url: 'https://example.com' } }; - const urlForTag = require('../../../dist/plugins/tag/url_for')(ctx); + const urlForTag = tagUrlFor(ctx); const urlFor = args => urlForTag(args.split(' ')); it('should encode path', () => { ctx.config.root = '/'; let $ = cheerio.load(urlFor('foo fôo.html')); - $('a').attr('href').should.eql('/f%C3%B4o.html'); - $('a').html().should.eql('foo'); + $('a').attr('href')!.should.eql('/f%C3%B4o.html'); + $('a').html()!.should.eql('foo'); ctx.config.root = '/fôo/'; $ = cheerio.load(urlFor('foo bár.html')); - $('a').attr('href').should.eql('/f%C3%B4o/b%C3%A1r.html'); - $('a').html().should.eql('foo'); + $('a').attr('href')!.should.eql('/f%C3%B4o/b%C3%A1r.html'); + $('a').html()!.should.eql('foo'); }); it('internal url (relative off)', () => { ctx.config.root = '/'; let $ = cheerio.load(urlFor('index index.html')); - $('a').attr('href').should.eql('/index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/index.html'); + $('a').html()!.should.eql('index'); $ = cheerio.load(urlFor('index /')); - $('a').attr('href').should.eql('/'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/'); + $('a').html()!.should.eql('index'); $ = cheerio.load(urlFor('index /index.html')); - $('a').attr('href').should.eql('/index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/index.html'); + $('a').html()!.should.eql('index'); ctx.config.root = '/blog/'; $ = cheerio.load(urlFor('index index.html')); - $('a').attr('href').should.eql('/blog/index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/blog/index.html'); + $('a').html()!.should.eql('index'); $ = cheerio.load(urlFor('index /')); - $('a').attr('href').should.eql('/blog/'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/blog/'); + $('a').html()!.should.eql('index'); $ = cheerio.load(urlFor('index /index.html')); - $('a').attr('href').should.eql('/blog/index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/blog/index.html'); + $('a').html()!.should.eql('index'); }); it('internal url (relative on)', () => { @@ -56,13 +55,13 @@ describe('url_for', () => { ctx.path = ''; let $ = cheerio.load(urlFor('index index.html')); - $('a').attr('href').should.eql('index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('index.html'); + $('a').html()!.should.eql('index'); ctx.path = 'foo/bar/'; $ = cheerio.load(urlFor('index index.html')); - $('a').attr('href').should.eql('../../index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('../../index.html'); + $('a').html()!.should.eql('index'); ctx.config.relative_link = false; }); @@ -70,34 +69,34 @@ describe('url_for', () => { it('internal url (options.relative)', () => { ctx.path = ''; let $ = cheerio.load(urlFor('index index.html true')); - $('a').attr('href').should.eql('index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('index.html'); + $('a').html()!.should.eql('index'); ctx.config.relative_link = true; $ = cheerio.load(urlFor('index index.html false')); - $('a').attr('href').should.eql('/index.html'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/index.html'); + $('a').html()!.should.eql('index'); ctx.config.relative_link = false; }); - it('internel url (pretty_urls.trailing_index disabled)', () => { + it('internal url (pretty_urls.trailing_index disabled)', () => { ctx.config.pretty_urls = { trailing_index: false }; ctx.path = ''; ctx.config.root = '/'; let $ = cheerio.load(urlFor('index index.html')); - $('a').attr('href').should.eql('/'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/'); + $('a').html()!.should.eql('index'); $ = cheerio.load(urlFor('index /index.html')); - $('a').attr('href').should.eql('/'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/'); + $('a').html()!.should.eql('index'); ctx.config.root = '/blog/'; $ = cheerio.load(urlFor('index index.html')); - $('a').attr('href').should.eql('/blog/'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/blog/'); + $('a').html()!.should.eql('index'); $ = cheerio.load(urlFor('index /index.html')); - $('a').attr('href').should.eql('/blog/'); - $('a').html().should.eql('index'); + $('a').attr('href')!.should.eql('/blog/'); + $('a').html()!.should.eql('index'); }); it('external url', () => { @@ -108,14 +107,14 @@ describe('url_for', () => { '//google.com/index.html' ].forEach(url => { const $ = cheerio.load(urlFor(`external ${url}`)); - $('a').attr('href').should.eql(url); - $('a').html().should.eql('external'); + $('a').attr('href')!.should.eql(url); + $('a').html()!.should.eql('external'); }); }); it('only hash', () => { const $ = cheerio.load(urlFor('hash #test')); - $('a').attr('href').should.eql('#test'); - $('a').html().should.eql('hash'); + $('a').attr('href')!.should.eql('#test'); + $('a').html()!.should.eql('hash'); }); }); diff --git a/test/scripts/theme/index.js b/test/scripts/theme/index.js deleted file mode 100644 index f6870aba8d..0000000000 --- a/test/scripts/theme/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -describe('Theme', () => { - require('./theme'); - require('./view'); -}); diff --git a/test/scripts/theme/theme.js b/test/scripts/theme/theme.ts similarity index 88% rename from test/scripts/theme/theme.js rename to test/scripts/theme/theme.ts index fc3b498cf7..faeab00bee 100644 --- a/test/scripts/theme/theme.js +++ b/test/scripts/theme/theme.ts @@ -1,10 +1,10 @@ -'use strict'; - -const { join } = require('path'); -const { mkdirs, rmdir, writeFile } = require('hexo-fs'); +import { join } from 'path'; +import { mkdirs, rmdir, writeFile } from 'hexo-fs'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('Theme', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'theme_test'), {silent: true}); const themeDir = join(hexo.base_dir, 'themes', 'test'); diff --git a/test/scripts/theme/view.js b/test/scripts/theme/view.ts similarity index 96% rename from test/scripts/theme/view.js rename to test/scripts/theme/view.ts index 20d1a60aa9..bc3d01ff45 100644 --- a/test/scripts/theme/view.js +++ b/test/scripts/theme/view.ts @@ -1,12 +1,12 @@ -'use strict'; - -const { join } = require('path'); -const { mkdirs, rmdir, writeFile } = require('hexo-fs'); -const moment = require('moment'); -const { fake, assert: sinonAssert } = require('sinon'); +import { join } from 'path'; +import { mkdirs, rmdir, writeFile } from 'hexo-fs'; +import moment from 'moment'; +import { fake, assert as sinonAssert } from 'sinon'; +import Hexo from '../../../lib/hexo'; +import chai from 'chai'; +const should = chai.should(); describe('View', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'theme_test')); const themeDir = join(hexo.base_dir, 'themes', 'test'); const { compile } = Object.assign({}, hexo.extend.renderer.store.njk); diff --git a/test/scripts/theme_processors/config.js b/test/scripts/theme_processors/config.ts similarity index 74% rename from test/scripts/theme_processors/config.js rename to test/scripts/theme_processors/config.ts index 34a61330de..1a3bdb5b7c 100644 --- a/test/scripts/theme_processors/config.js +++ b/test/scripts/theme_processors/config.ts @@ -1,15 +1,18 @@ -'use strict'; - -const { spy, assert: sinonAssert } = require('sinon'); -const { join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile} = require('hexo-fs'); -const Promise = require('bluebird'); +import { spy, assert as sinonAssert } from 'sinon'; +import { join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile} from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import { config } from '../../../lib/theme/processors/config'; +import chai from 'chai'; +const should = chai.should(); +type ConfigParams = Parameters +type ConfigReturn = ReturnType describe('config', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'config_test'), {silent: true}); - const processor = require('../../../dist/theme/processors/config'); - const process = Promise.method(processor.config.process.bind(hexo)); + const process: (...args: ConfigParams) => Promise = Promise.method(config.process.bind(hexo)); const themeDir = join(hexo.base_dir, 'themes', 'test'); function newFile(options) { @@ -30,7 +33,7 @@ describe('config', () => { after(() => rmdir(hexo.base_dir)); it('pattern', () => { - const pattern = processor.config.pattern; + const pattern = config.pattern; pattern.match('_config.yml').should.be.ok; pattern.match('_config.json').should.be.ok; diff --git a/test/scripts/theme_processors/i18n.js b/test/scripts/theme_processors/i18n.ts similarity index 71% rename from test/scripts/theme_processors/i18n.js rename to test/scripts/theme_processors/i18n.ts index 84088e31af..edb1d6b3c4 100644 --- a/test/scripts/theme_processors/i18n.js +++ b/test/scripts/theme_processors/i18n.ts @@ -1,14 +1,17 @@ -'use strict'; - -const { join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); +import { join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import { i18n } from '../../../lib/theme/processors/i18n'; +import chai from 'chai'; +const should = chai.should(); +type I18nParams = Parameters +type I18nReturn = ReturnType describe('i18n', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'config_test'), {silent: true}); - const processor = require('../../../dist/theme/processors/i18n'); - const process = Promise.method(processor.i18n.process.bind(hexo)); + const process: (...args: I18nParams) => Promise = Promise.method(i18n.process.bind(hexo)); const themeDir = join(hexo.base_dir, 'themes', 'test'); function newFile(options) { @@ -33,7 +36,7 @@ describe('i18n', () => { after(() => rmdir(hexo.base_dir)); it('pattern', () => { - const pattern = processor.i18n.pattern; + const pattern = i18n.pattern; pattern.match('languages/default.yml').should.be.ok; pattern.match('languages/zh-TW.yml').should.be.ok; @@ -54,7 +57,7 @@ describe('i18n', () => { await writeFile(file.source, body); await process(file); - const __ = hexo.theme.i18n.__('en'); + const __ = hexo.theme.i18n.__('en' as any); __('ok').should.eql('OK'); __('index.title').should.eql('Home'); diff --git a/test/scripts/theme_processors/index.js b/test/scripts/theme_processors/index.js deleted file mode 100644 index e21a45848c..0000000000 --- a/test/scripts/theme_processors/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -describe('Theme processors', () => { - require('./config'); - require('./i18n'); - require('./source'); - require('./view'); -}); diff --git a/test/scripts/theme_processors/source.js b/test/scripts/theme_processors/source.ts similarity index 85% rename from test/scripts/theme_processors/source.js rename to test/scripts/theme_processors/source.ts index b84546e3d0..9b4f6f2979 100644 --- a/test/scripts/theme_processors/source.js +++ b/test/scripts/theme_processors/source.ts @@ -1,14 +1,17 @@ -'use strict'; - -const { join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); +import { join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import { source } from '../../../lib/theme/processors/source'; +import chai from 'chai'; +const should = chai.should(); +type SourceParams = Parameters +type SourceReturn = ReturnType describe('source', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'source_test'), {silent: true}); - const processor = require('../../../dist/theme/processors/source'); - const process = Promise.method(processor.source.process.bind(hexo)); + const process: (...args: SourceParams) => Promise = Promise.method(source.process.bind(hexo)); const themeDir = join(hexo.base_dir, 'themes', 'test'); const Asset = hexo.model('Asset'); @@ -33,7 +36,7 @@ describe('source', () => { after(() => rmdir(hexo.base_dir)); it('pattern', () => { - const { pattern } = processor.source; + const { pattern } = source; pattern.match('source/foo.jpg').should.eql({path: 'foo.jpg'}); pattern.match('source/_foo.jpg').should.be.false; diff --git a/test/scripts/theme_processors/view.js b/test/scripts/theme_processors/view.ts similarity index 75% rename from test/scripts/theme_processors/view.js rename to test/scripts/theme_processors/view.ts index 145fc85f8e..1b7c254af9 100644 --- a/test/scripts/theme_processors/view.js +++ b/test/scripts/theme_processors/view.ts @@ -1,14 +1,18 @@ -'use strict'; +import { join } from 'path'; +import { mkdirs, rmdir, unlink, writeFile } from 'hexo-fs'; +// @ts-ignore +import Promise from 'bluebird'; +import Hexo from '../../../lib/hexo'; +import { view } from '../../../lib/theme/processors/view'; +import chai from 'chai'; +const should = chai.should(); +type ViewParams = Parameters +type ViewReturn = ReturnType -const { join } = require('path'); -const { mkdirs, rmdir, unlink, writeFile } = require('hexo-fs'); -const Promise = require('bluebird'); describe('view', () => { - const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'view_test'), {silent: true}); - const processor = require('../../../dist/theme/processors/view'); - const process = Promise.method(processor.view.process.bind(hexo)); + const process: (...args: ViewParams) => Promise = Promise.method(view.process.bind(hexo)); const themeDir = join(hexo.base_dir, 'themes', 'test'); hexo.env.init = true; @@ -34,7 +38,7 @@ describe('view', () => { after(() => rmdir(hexo.base_dir)); it('pattern', () => { - const { pattern } = processor.view; + const { pattern } = view; pattern.match('layout/index.njk').path.should.eql('index.njk'); should.not.exist(pattern.match('index.njk')); diff --git a/test/util/.eslintrc b/test/util/.eslintrc new file mode 100644 index 0000000000..f25990b7d4 --- /dev/null +++ b/test/util/.eslintrc @@ -0,0 +1,6 @@ +{ + "extends": "hexo/ts", + "rules": { + "node/no-unsupported-features/es-syntax": 0 + } +} \ No newline at end of file diff --git a/test/util/index.js b/test/util/index.js deleted file mode 100644 index 1d03088e3e..0000000000 --- a/test/util/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -exports.stream = require('./stream'); diff --git a/test/util/index.ts b/test/util/index.ts new file mode 100644 index 0000000000..2e9c6cef28 --- /dev/null +++ b/test/util/index.ts @@ -0,0 +1 @@ +export { readStream } from './stream'; diff --git a/test/util/stream.js b/test/util/stream.ts similarity index 65% rename from test/util/stream.js rename to test/util/stream.ts index 930e4ccdc4..e53e9d8a30 100644 --- a/test/util/stream.js +++ b/test/util/stream.ts @@ -1,8 +1,6 @@ -'use strict'; +import Promise from 'bluebird'; -const Promise = require('bluebird'); - -function readStream(stream) { +export function readStream(stream): Promise { return new Promise((resolve, reject) => { let data = ''; @@ -13,5 +11,3 @@ function readStream(stream) { }).on('error', reject); }); } - -exports.read = readStream; diff --git a/tsconfig.json b/tsconfig.json index 44cec41e42..78046e5376 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,7 +7,8 @@ "declaration": true, "esModuleInterop": true, "types": [ - "node" + "node", + "mocha" ] }, "include": [