Skip to content

Commit

Permalink
Merge pull request jd-opensource#442 from LinFeng1997/lifecycles_even…
Browse files Browse the repository at this point in the history
…t_test

test: lifecycles event
  • Loading branch information
bailicangdu authored Jun 22, 2022
2 parents 8052b5f + 40cfb96 commit 3438bc9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:unit": "jest src/__tests__/unit",
"test:unit:coverage": "npm run test:unit -- --coverage",
"prepublishOnly": "yarn lint && yarn test && yarn build"
},
"repository": {
Expand Down
53 changes: 53 additions & 0 deletions src/__tests__/unit/lifecycles_event.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

import dispatchLifecyclesEvent, { dispatchCustomEventToMicroApp } from '../../interact/lifecycles_event'
import microApp from '../../micro_app'

describe('LifeCycles Event', () => {
describe('dispatchCustomEventToMicroApp', () => {
test('使用 dispatchCustomEventToMicroApp 方法发送事件,window 可以接收到事件', () => {
const callback = jest.fn()
window.addEventListener('event-app', callback)

dispatchCustomEventToMicroApp('event', 'app')

expect(callback).toBeCalled()
})
})

describe('dispatchLifecyclesEvent', () => {
const appName = 'app'
beforeAll(() => {
console.error = jest.fn()
})

test('element 为空,报错', () => {
// @ts-ignore
dispatchLifecyclesEvent(undefined, appName, 'mount')

expect(console.error).toBeCalledWith(`[micro-app] app ${appName}: element does not exist in lifecycle mount`)
})

test('发送 mount 事件,接收成功', () => {
const container = document.createElement('div')
container.addEventListener('mount', (e) => {
const { name, container: detailContainer } = (e as CustomEvent).detail
expect(name).toEqual(appName)
expect(detailContainer).toEqual(container)
expect(e.target).toEqual(container)
expect(e.currentTarget).toEqual(container)
})
dispatchLifecyclesEvent(container, appName, 'mount')
})

test('发送 created 事件,主应用监听了这个事件可以被触发', () => {
const container = document.createElement('div')
const onCreated = jest.fn()

microApp.lifeCycles = { created: onCreated }
dispatchLifecyclesEvent(container, appName, 'created')

expect(onCreated).toBeCalled()
microApp.lifeCycles = undefined
})
})
})

0 comments on commit 3438bc9

Please sign in to comment.