Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: link-loader refactor #451

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/__tests__/unit/mocks/link.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,22 @@
import { sourceLinkInfo } from '@micro-app/types'

export const MOCK_CSS = `
div {
color: red;
}
`

export const MOCK_CSS_URL = 'http://www.abc.com/common.css'
export const MOCK_ERROR_CSS_URL = 'http://www.abc.com/error.css'

export const MOCK_CSS_LINK_INFO: sourceLinkInfo = {
code: '',
isGlobal: false,
placeholder: document.createComment('placeholder for link with href=common'),
}

export const MOCK_ERROR_CSS_LINK_INFO: sourceLinkInfo = {
code: '',
isGlobal: false,
placeholder: document.createComment('placeholder for link with href=error'),
}
81 changes: 81 additions & 0 deletions src/__tests__/unit/source/loader/link.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,81 @@
import { waitFor } from '../../../common/util'
import {
MOCK_CSS,
MOCK_CSS_LINK_INFO,
MOCK_CSS_URL,
MOCK_ERROR_CSS_LINK_INFO,
MOCK_ERROR_CSS_URL,
} from '../../mocks/link'
import { setupMockFetch } from '../../mocks/fetch'
import { LinkLoader } from '../../../../source/loader/link'
import { MOCK_APP_URL } from '../../mocks/app'
import { AppInterface } from '@micro-app/types'

const setup = (data: string) => {
const mockFetch = (url: string) => {
if (url === MOCK_ERROR_CSS_URL) {
return setupMockFetch(data, true)()
}
return setupMockFetch(data)()
}
global.fetch = jest.fn().mockImplementation(mockFetch)
const linkLoader = LinkLoader.getInstance()
const successCb = jest.fn()
const errorCb = jest.fn()
const finallyCb = jest.fn()

return {
linkLoader,
successCb,
errorCb,
finallyCb,
}
}

describe('LinkLoader', () => {
beforeAll(() => {
console.error = jest.fn()
})

test('给定一个链接集数据,可以获取到 css 字符串', async () => {
const { linkLoader, successCb, finallyCb } = setup(MOCK_CSS)
const links = new Map()
const app = {
name: 'app-1',
url: MOCK_APP_URL,
source: {
links
}
} as AppInterface
links.set(MOCK_CSS_URL, MOCK_CSS_LINK_INFO)

linkLoader.run(app, successCb, finallyCb)

await waitFor(() => {
expect(successCb).toBeCalledWith(MOCK_CSS_URL, MOCK_CSS_LINK_INFO, MOCK_CSS)
expect(finallyCb).toBeCalled()
})
})

test('给定一个链接集数据,里面有多个链接信息,其中有一个会发生网络错误,会执行 errorCb 回调和 finallyCb 回调', async () => {
const { linkLoader, successCb, finallyCb } = setup(MOCK_CSS)
const links = new Map()
const app = {
name: 'app-1',
url: MOCK_APP_URL,
source: {
links
}
} as AppInterface
links.set(MOCK_CSS_URL, MOCK_CSS_LINK_INFO)
links.set(MOCK_ERROR_CSS_URL, MOCK_ERROR_CSS_LINK_INFO)

linkLoader.run(app, successCb, finallyCb)

const logError = jest.spyOn(console, 'error')
await waitFor(() => {
expect(logError).toBeCalled()
expect(finallyCb).toBeCalled()
})
})
})
17 changes: 14 additions & 3 deletions src/source/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 1,11 @@
import type { AppInterface } from '@micro-app/types'
import type { AppInterface, sourceLinkInfo } from '@micro-app/types'
import {
logError,
CompletionPath,
pureCreateElement,
} from '../libs/utils'
import { extractLinkFromHtml, fetchLinksFromHtml } from './links'
import { extractLinkFromHtml, fetchLinkSuccess } from './links'
import { LinkLoader } from './loader/link'
import { extractScriptElement, fetchScriptsFromHtml, checkExcludeUrl, checkIgnoreUrl } from './scripts'
import scopedCSS from './scoped_css'

Expand Down Expand Up @@ -81,7 82,17 @@ export function extractSourceDom (htmlStr: string, app: AppInterface) {
flatChildren(wrapElement, app, microAppHead)

if (app.source.links.size) {
fetchLinksFromHtml(wrapElement, app, microAppHead)
LinkLoader.getInstance().run(app, (url: string, info: sourceLinkInfo, data: string) => {
fetchLinkSuccess(
url,
info,
data,
microAppHead,
app,
)
}, () => {
app.onLoad(wrapElement)
})
} else {
app.onLoad(wrapElement)
}
Expand Down
33 changes: 0 additions & 33 deletions src/source/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 5,6 @@ import type {
import { fetchSource } from './fetch'
import {
CompletionPath,
promiseStream,
pureCreateElement,
defer,
logError,
Expand Down Expand Up @@ -73,38 72,6 @@ export function extractLinkFromHtml (
}
}

/**
* Get link remote resources
* @param wrapElement htmlDom
* @param app app
* @param microAppHead micro-app-head
*/
export function fetchLinksFromHtml (
wrapElement: HTMLElement,
app: AppInterface,
microAppHead: Element,
): void {
const linkEntries: Array<[string, sourceLinkInfo]> = Array.from(app.source.links.entries())

const fetchLinkPromise: Array<Promise<string>|string> = linkEntries.map(([url]) => {
return globalLinks.has(url) ? globalLinks.get(url)! : fetchSource(url, app.name)
})

promiseStream<string>(fetchLinkPromise, (res: {data: string, index: number}) => {
fetchLinkSuccess(
linkEntries[res.index][0],
linkEntries[res.index][1],
res.data,
microAppHead,
app,
)
}, (err: {error: Error, index: number}) => {
logError(err, app.name)
}, () => {
app.onLoad(wrapElement)
})
}

/**
* fetch link succeeded, replace placeholder with style tag
* @param url resource address
Expand Down
62 changes: 62 additions & 0 deletions src/source/loader/link.ts
Original file line number Diff line number Diff line change
@@ -0,0 1,62 @@
import { AppInterface, sourceLinkInfo } from '@micro-app/types'
import { fetchSource } from '../fetch'
import { logError, promiseStream } from '../../libs/utils'
import { globalLinks } from '../links'

export interface ILinkLoader {
run (
app: AppInterface,
successCb: CallableFunction,
finallyCb: CallableFunction
): void
}

export class LinkLoader implements ILinkLoader {
private static instance: LinkLoader;
public static getInstance (): LinkLoader {
if (!this.instance) {
this.instance = new LinkLoader()
}
return this.instance
}

/**
* Get link remote resources
* @param app app
* @param successCb success callback
* @param finallyCb finally callback
*/
public run (
app: AppInterface,
successCb: CallableFunction,
finallyCb: CallableFunction
): void {
const {
linkEntries,
fetchLinkPromise
} = this.getLinkData(app)

promiseStream<string>(fetchLinkPromise, (res: {data: string, index: number}) => {
const [url, info] = linkEntries[res.index]

successCb(url, info, res.data)
}, (err: {error: Error, index: number}) => {
logError(err, app.name)
}, () => {
finallyCb?.()
})
}

private getLinkData (app: AppInterface) {
const linkEntries: Array<[string, sourceLinkInfo]> = Array.from(app.source.links.entries())

const fetchLinkPromise: Array<Promise<string>|string> = linkEntries.map(([url]) => {
return globalLinks.has(url) ? globalLinks.get(url)! : fetchSource(url, app.name)
})

return {
linkEntries,
fetchLinkPromise
}
}
}