Files
o2o-weather/frontend/tests/embedLoader.test.mjs
T
skkim dc8201e5f5 feat: 다른 사이트에 붙이는 날씨각 위젯 — 누구나 붙이는 카드(/embed/card, 기본형·상세형, 배경 3종)와 사용 방법 페이지(/widget, 스크립트·iframe 코드)
- 카드: 군산각 카드를 옮겨 그림, 토끼 로딩, 실패하면 '날씨각에서 날씨 보기' 링크, 8초 제한, nginx 대체 화면, '자세히 보기' 버튼만 링크
- 크기: 폭은 자리에 맞춰 자동, 높이는 폭에 따라 비율대로(기본형 245~320px, 상세형 400~520px)
- 부하: 지역별 카드 데이터 5분 저장, 저장분이 비면 지역마다 한 요청만 새로 만듦, 노출 수는 Redis 에 쌓았다가 관리자 조회 때 DB(widget_view_daily)로 옮김
- 사용 방법 페이지: 지역(앱 지역은 바꾸지 않음)·모양·배경 고르기, 미리보기, 코드 복사. 들어오는 길은 문의 창 버튼(토스에서는 숨김)과 검색
- GA: 위젯_안내_보기, 위젯_옵션_고름, 위젯_코드_복사
- 문서: docs/위젯_운영.md, 백엔드 테스트 실행법(CLAUDE.md)
2026-11-26 13:03:29 +09:00

181 lines
7.3 KiB
JavaScript

// 다른 사이트에 붙이는 스크립트(public/embed/widget.js) 검증: 가짜 문서에서 돌려 링크 자리에 생긴 iframe 이
// embedCode 가 만드는 iframe 과 같은지 본다 (크기 상수가 두 파일에서 어긋나지 않게 묶는다). 실행: frontend 폴더에서 npm test
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
import vm from 'node:vm'
import { embedCode } from '../src/lib/embedWidget.ts'
const SOURCE = readFileSync(new URL('../public/embed/widget.js', import.meta.url), 'utf8')
const SCRIPT_SRC = 'http://localhost:8080/embed/widget.js'
const ORIGIN = 'http://localhost:8080'
/** 가짜 요소: 속성·글자·부모만 */
function node(tag, attrs = {}, text = '') {
return {
tagName: tag.toUpperCase(),
attrs: { ...attrs },
textContent: text,
parentNode: null,
getAttribute(name) {
return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null
},
setAttribute(name, value) {
this.attrs[name] = String(value)
},
}
}
/** 날씨각 링크 */
function link(attrs, text = '군산시 날씨 - 날씨각') {
return node('a', { class: 'nalssigak-weather', href: 'https://weather.o2o.kr/today/jeonbuk/gunsan', ...attrs }, text)
}
// widget.js 가 쓰는 선택자만 안다
const SELECTORS = {
'a.nalssigak-weather[data-region]': (n) => n.tagName === 'A' && (n.attrs.class ?? '').split(/\s+/).includes('nalssigak-weather') && Object.hasOwn(n.attrs, 'data-region'),
'script[src*="/embed/widget.js"]': (n) => n.tagName === 'SCRIPT' && (n.attrs.src ?? '').includes('/embed/widget.js'),
}
/** 가짜 문서: body 아래에 링크들과 스크립트 태그가 나란히 있다 */
function fakeDoc(links, { scriptSrc = SCRIPT_SRC, current = true, readyState = 'complete' } = {}) {
const listeners = {}
const body = {
children: [],
replaceChild(next, old) {
const i = this.children.indexOf(old)
if (i < 0) throw new Error('없는 자식을 바꾸려 함')
this.children[i] = next
next.parentNode = this
old.parentNode = null
return old
},
}
const script = node('script', { src: scriptSrc, async: '' })
script.src = scriptSrc // 브라우저는 src 속성(프로퍼티)에 절대 주소를 준다
for (const n of [...links, script]) {
n.parentNode = body
body.children.push(n)
}
const doc = {
readyState,
currentScript: current ? script : null,
createElement: (tag) => node(tag),
querySelectorAll(sel) {
const match = SELECTORS[sel]
if (!match) throw new Error(`모르는 선택자 ${sel}`)
return body.children.filter(match)
},
addEventListener(type, fn) {
;(listeners[type] ??= []).push(fn)
},
}
return {
doc,
body,
fire: (type) => (listeners[type] ?? []).forEach((fn) => fn()),
frames: () => body.children.filter((n) => n.tagName === 'IFRAME'),
}
}
/** 브라우저처럼 문서만 주고 widget.js 를 돌린다 (console·window 없음: 쓰면 오류로 드러난다) */
function run(doc) {
vm.runInNewContext(SOURCE, { document: doc })
}
/** embedCode 문자열의 iframe 속성 (HTML 이스케이프를 푼 값) */
function attrsOf(html) {
const out = {}
for (const [, name, value] of html.matchAll(/([a-z]+)="([^"]*)"/g)) {
out[name] = value.replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
}
return out
}
test('올바른 링크 → 그 자리에 iframe 하나, 속성은 embedCode 와 같다', () => {
for (const kind of ['side', 'home']) {
for (const bg of ['sky', 'light', 'dark']) {
const a = link({ 'data-region': '5213000000', 'data-type': kind, 'data-bg': bg })
const page = fakeDoc([a])
run(page.doc)
assert.equal(page.frames().length, 1)
assert.equal(page.body.children[0], page.frames()[0], '링크가 있던 자리')
assert.equal(a.parentNode, null, '링크는 빠진다')
assert.deepEqual(page.frames()[0].attrs, attrsOf(embedCode({ origin: ORIGIN, region: '5213000000', regionName: '군산시', kind, bg })))
}
}
})
test('iframe 제목은 링크 글자 (특수문자도 그대로)', () => {
const page = fakeDoc([link({ 'data-region': '5213000000' }, 'A&B<C>"D 날씨 - 날씨각')])
run(page.doc)
assert.deepEqual(page.frames()[0].attrs, attrsOf(embedCode({ origin: ORIGIN, region: '5213000000', regionName: 'A&B<C>"D', kind: 'side', bg: 'sky' })))
})
test('data-type·data-bg 를 빼면 기본형(side)·기본형 배경(sky)', () => {
const page = fakeDoc([link({ 'data-region': '5213000000' })])
run(page.doc)
assert.equal(page.frames()[0].attrs.src, `${ORIGIN}/embed/card?region=5213000000&type=side&bg=sky`)
assert.equal(page.frames()[0].attrs.height, '245')
assert.equal(page.frames()[0].attrs.style, 'border:0;width:100%;height:auto;aspect-ratio:11/8;min-width:220px;max-width:440px;min-height:245px;max-height:320px;border-radius:28px')
})
test('틀린 지역·모양·배경의 링크는 그대로 둔다', () => {
const bad = [
link({ 'data-region': '521300000' }),
link({ 'data-region': '52130000001' }),
link({ 'data-region': '52130000ab' }),
link({ 'data-region': '5213000000', 'data-type': 'wide' }),
link({ 'data-region': '5213000000', 'data-bg': 'red' }),
]
const page = fakeDoc(bad)
run(page.doc)
assert.equal(page.frames().length, 0)
assert.deepEqual(page.body.children.slice(0, bad.length), bad)
})
test('두 번 실행해도 iframe 은 하나', () => {
const page = fakeDoc([link({ 'data-region': '5213000000' })])
run(page.doc)
run(page.doc)
assert.equal(page.frames().length, 1)
})
test('링크가 여러 개면 각각 생긴다', () => {
const page = fakeDoc([link({ 'data-region': '5213000000', 'data-type': 'home' }), link({ 'data-region': '1111000000', 'data-bg': 'dark' }, '종로구 날씨 - 날씨각')])
run(page.doc)
assert.deepEqual(
page.frames().map((f) => f.attrs.src),
[`${ORIGIN}/embed/card?region=5213000000&type=home&bg=sky`, `${ORIGIN}/embed/card?region=1111000000&type=side&bg=dark`],
)
assert.equal(page.frames()[1].attrs.title, '종로구 날씨 - 날씨각')
})
test('날씨각 주소(origin)는 스크립트 주소에서 온다', () => {
const page = fakeDoc([link({ 'data-region': '5213000000' })], { scriptSrc: 'https://weather.o2o.kr/embed/widget.js' })
run(page.doc)
assert.equal(page.frames()[0].attrs.src, 'https://weather.o2o.kr/embed/card?region=5213000000&type=side&bg=sky')
})
test('currentScript 가 없으면 스크립트 태그를 찾아 주소를 얻는다', () => {
const page = fakeDoc([link({ 'data-region': '5213000000' })], { current: false })
run(page.doc)
assert.equal(page.frames()[0].attrs.src, `${ORIGIN}/embed/card?region=5213000000&type=side&bg=sky`)
})
test('문서가 다 읽히기 전에 실행되면 다 읽힌 뒤에도 한 번 더 찾는다', () => {
const page = fakeDoc([], { readyState: 'loading' })
run(page.doc)
// 스크립트보다 아래에 있어 나중에 읽힌 링크
const late = link({ 'data-region': '5213000000' })
late.parentNode = page.body
page.body.children.push(late)
page.fire('DOMContentLoaded')
assert.equal(page.frames().length, 1)
})
test('옛 브라우저에서도 돌게 ES5 문법만 쓴다', () => {
const code = SOURCE.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '')
assert.doesNotMatch(code, /=>|`|\b(?:let|const|class)\s/)
})