|
1 | | -import { describe, expect, test } from 'vitest' |
2 | | -import { getAcceptLanguages, getCookieLocale, getLocale } from '../src/index.ts' |
| 1 | +import { beforeEach, describe, expect, test } from 'vitest' |
| 2 | +import { createApp, eventHandler, toNodeListener } from 'h3' |
| 3 | +import supertest from 'supertest' |
| 4 | +import { |
| 5 | + getAcceptLanguages, |
| 6 | + getCookieLocale, |
| 7 | + getLocale, |
| 8 | + setCookieLocale, |
| 9 | +} from '../src/index.ts' |
3 | 10 |
|
4 | | -import type { H3Event } from 'h3' |
| 11 | +import type { App, H3Event } from 'h3' |
| 12 | +import type { SuperTest, Test } from 'supertest' |
5 | 13 |
|
6 | 14 | describe('getAcceptLanguages', () => { |
7 | 15 | test('basic', () => { |
@@ -191,3 +199,70 @@ describe('getCookieLocale', () => { |
191 | 199 | .toThrowError(RangeError) |
192 | 200 | }) |
193 | 201 | }) |
| 202 | + |
| 203 | +describe('setCookieLocale', () => { |
| 204 | + let app: App |
| 205 | + let request: SuperTest<Test> |
| 206 | + |
| 207 | + beforeEach(() => { |
| 208 | + app = createApp({ debug: false }) |
| 209 | + request = supertest(toNodeListener(app)) |
| 210 | + }) |
| 211 | + |
| 212 | + test('specify Locale instance', async () => { |
| 213 | + app.use( |
| 214 | + '/', |
| 215 | + eventHandler((event) => { |
| 216 | + const locale = new Intl.Locale('ja-JP') |
| 217 | + setCookieLocale(event, locale) |
| 218 | + return '200' |
| 219 | + }), |
| 220 | + ) |
| 221 | + const result = await request.get('/') |
| 222 | + expect(result.headers['set-cookie']).toEqual([ |
| 223 | + 'i18n_locale=ja-JP; Path=/', |
| 224 | + ]) |
| 225 | + }) |
| 226 | + |
| 227 | + test('specify language tag', async () => { |
| 228 | + app.use( |
| 229 | + '/', |
| 230 | + eventHandler((event) => { |
| 231 | + setCookieLocale(event, 'ja-JP') |
| 232 | + return '200' |
| 233 | + }), |
| 234 | + ) |
| 235 | + const result = await request.get('/') |
| 236 | + expect(result.headers['set-cookie']).toEqual([ |
| 237 | + 'i18n_locale=ja-JP; Path=/', |
| 238 | + ]) |
| 239 | + }) |
| 240 | + |
| 241 | + test('specify cookie name', async () => { |
| 242 | + app.use( |
| 243 | + '/', |
| 244 | + eventHandler((event) => { |
| 245 | + setCookieLocale(event, 'ja-JP', { name: 'intlify_locale' }) |
| 246 | + return '200' |
| 247 | + }), |
| 248 | + ) |
| 249 | + const result = await request.get('/') |
| 250 | + expect(result.headers['set-cookie']).toEqual([ |
| 251 | + 'intlify_locale=ja-JP; Path=/', |
| 252 | + ]) |
| 253 | + }) |
| 254 | + |
| 255 | + test('Syntax Error', () => { |
| 256 | + const eventMock = { |
| 257 | + node: { |
| 258 | + req: { |
| 259 | + method: 'GET', |
| 260 | + headers: {}, |
| 261 | + }, |
| 262 | + }, |
| 263 | + } as H3Event |
| 264 | + |
| 265 | + expect(() => setCookieLocale(eventMock, 'j')) |
| 266 | + .toThrowError(/locale is invalid: j/) |
| 267 | + }) |
| 268 | +}) |
0 commit comments