[Javascript] Test a web component
import { WatermarkOverlay } from '../watermark-overlay'
describe('WatermarkOverlay', () => {
let cmp: HTMLElement
let fixture: HTMLElement
let shadow: ShadowRoot | null | undefined
customElements.define('test-watermarkoverlay', WatermarkOverlay)
beforeEach(() => {
Object.defineProperty(window, 'innerWidth', {
writable: true,
value: 1024,
})
Object.defineProperty(window, 'innerHeight', {
writable: true,
value: 768,
})
document.body.innerHTML = `<div id="fixture"><test-watermarkoverlay userId="testUserId" message="testMessage"></test-watermarkoverlay></div>`
fixture = document.querySelector('#fixture')!
cmp = document.querySelector('test-watermarkoverlay')!
cmp.setAttribute('size', '1024:768')
shadow = cmp?.shadowRoot
})
afterEach(() => {
shadow = null
fixture.remove()
})
test('should have the container', () => {
const container = shadow?.querySelector('.zscaler__overlay--container')
expect(container).toBeDefined()
const styles = window.getComputedStyle(container!)
const { zIndex } = styles
expect(zIndex).toBe('99999999999999')
})
test('should have watermark div elements', () => {
const container = shadow?.querySelector('.zscaler__overlay--container')
const elms = container?.querySelectorAll('.zscaler__overlay--watermark')
expect(elms?.length).toBeGreaterThan(0)
const firstDiv = elms?.[0]
expect(firstDiv?.innerHTML).toContain('testUserId')
expect(firstDiv?.innerHTML).toContain('testMessage')
})
test('resize: if enlarge the window should increase the number of divs', (done) => {
let container = shadow?.querySelector('.zscaler__overlay--container')
let elms = container?.querySelectorAll('.zscaler__overlay--watermark')
const pervNum = elms?.length || 0
expect(pervNum).toBeGreaterThan(0)
cmp.setAttribute('size', '2048:768')
setTimeout(() => {
container = shadow?.querySelector('.zscaler__overlay--container')
elms = container?.querySelectorAll('.zscaler__overlay--watermark')
const currentNum = elms?.length
expect(currentNum).toBeGreaterThan(pervNum)
done()
}, 10)
})
test('resize: if narrow the window should NOT decrease the number of divs', (done) => {
let container = shadow?.querySelector('.zscaler__overlay--container')
let elms = container?.querySelectorAll('.zscaler__overlay--watermark')
const pervNum = elms?.length || 0
expect(pervNum).toBeGreaterThan(0)
cmp.setAttribute('size', '768:768')
setTimeout(() => {
container = shadow?.querySelector('.zscaler__overlay--container')
elms = container?.querySelectorAll('.zscaler__overlay--watermark')
const currentNum = elms?.length
expect(currentNum).toEqual(pervNum)
done()
}, 10)
})
test('should emit "watermarkRevmoed" event when remove the fixture', () => {
const cb = jest.fn()
cmp.addEventListener('watermarkRemoved', cb)
fixture.remove()
expect(cb).toHaveBeenCalled()
expect(cb).toHaveBeenCalledTimes(1)
})
})