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

refactor(context): remove unnecessary initialization add add tests for Context #2949

Merged
merged 2 commits into from
Jun 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
93 changes: 90 additions & 3 deletions src/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ describe('Context', () => {
expect(res.headers.get('X-Custom')).toBe('Message')
})

it('c.html() with async', async () => {
const res = await c.html(
new Promise((resolve) => setTimeout(() => resolve('<h1>Hello! Hono!</h1>'), 0)),
201,
{
'X-Custom': 'Message',
}
)
expect(res.status).toBe(201)
expect(res.headers.get('Content-Type')).toMatch('text/html')
expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')
expect(res.headers.get('X-Custom')).toBe('Message')
})

it('c.redirect()', async () => {
let res = c.redirect('/destination')
expect(res.status).toBe(302)
Expand All @@ -67,6 +81,18 @@ describe('Context', () => {
expect(foo).toBe('Bar, Buzz')
})

it('c.set() and c.get()', async () => {
expect(c.get('foo')).toBe(undefined)
c.set('foo', 'bar')
expect(c.get('foo')).toBe('bar')
expect(c.get('foo2')).toBe(undefined)
})

it('c.notFound()', async () => {
const res = c.notFound()
expect(res).instanceOf(Response)
})

it('Should set headers if already this.#headers is created by `c.header()`', async () => {
c.header('X-Foo', 'Bar')
c.header('X-Foo', 'Buzz', { append: true })
Expand Down Expand Up @@ -96,6 +122,12 @@ describe('Context', () => {
expect(res.headers.get('X-Foo2')).toBe(null)
})

it('c.header() - clear the header when append is true', async () => {
c.header('X-Foo', 'Bar', { append: true })
c.header('X-Foo', undefined)
expect(c.res.headers.get('X-Foo')).toBe(null)
})

it('c.body() - multiple header', async () => {
const res = c.body('Hi', 200, {
'X-Foo': ['Bar', 'Buzz'],
Expand Down Expand Up @@ -210,17 +242,64 @@ describe('Context', () => {
})
})

describe('event and executionCtx', () => {
const req = new HonoRequest(new Request('http://localhost/'))

it('Should return the event if accessing c.event', () => {
const respondWith = vi.fn()
const c = new Context(req, {
// @ts-expect-error the type is not correct
executionCtx: {
respondWith: respondWith,
},
})
expect(() => c.event).not.toThrowError()
c.event.respondWith(new Response())
expect(respondWith).toHaveBeenCalled()
})

it('Should throw an error if accessing c.event', () => {
const c = new Context(req)
expect(() => c.event).toThrowError()
})

it('Should return the executionCtx if accessing c.executionCtx', () => {
const pathThroughOnException = vi.fn()
const waitUntil = vi.fn()
const c = new Context(req, {
executionCtx: {
passThroughOnException: pathThroughOnException,
waitUntil: waitUntil,
},
env: {},
})
expect(() => c.executionCtx).not.toThrowError()
c.executionCtx.passThroughOnException()
expect(pathThroughOnException).toHaveBeenCalled()
const asyncFunc = async () => {}
c.executionCtx.waitUntil(asyncFunc())
expect(waitUntil).toHaveBeenCalled()
})

it('Should throw an error if accessing c.executionCtx', () => {
const c = new Context(req)
expect(() => c.executionCtx).toThrowError()
})
})

describe('Context header', () => {
const req = new HonoRequest(new Request('http://localhost/'))
let c: Context
beforeEach(() => {
c = new Context(req)
})

it('Should return only one content-type value', async () => {
c.header('Content-Type', 'foo')
const res = await c.html('foo')
expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')
})

it('Should rewrite header values correctly', async () => {
c.res = await c.html('foo')
const res = c.text('foo')
Expand All @@ -238,12 +317,20 @@ describe('Context header', () => {
})

it('Should set cookie headers when re-assigning Response to `c.res`', () => {
c.res = new Response(null)
const cookies = ['foo=bar; Path=/', 'foo2=bar2; Path=/']
const res = new Response(null)
res.headers.append('set-cookie', 'foo=bar; Path=/')
res.headers.append('set-cookie', 'foo2=bar2; Path=/')
res.headers.append('set-cookie', cookies[0])
res.headers.append('set-cookie', cookies[1])
c.res = res
expect(c.res.headers.getSetCookie().length).toBe(2)

// Re-assign
const newCookies = ['foo3=bar3; Path=/']
const newResponse = new Response(null)
newResponse.headers.append('set-cookie', newCookies[0])
c.res = newResponse
expect(c.res.headers.getSetCookie().length).toBe(cookies.length)
expect(c.res.headers.getSetCookie()).toEqual(cookies)
})

it('Should keep previous cookies in response headers', () => {
Expand Down
11 changes: 6 additions & 5 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,9 @@ export class Context<

/**
* `.set()` can set the value specified by the key.
*
*
* @see {@link https://hono.dev/api/context#set-get}
*
*
* @example
* ```ts
* app.use('*', async (c, next) => {
Expand All @@ -480,8 +480,8 @@ export class Context<
```
*/
set: Set<E> = (key: string, value: unknown) => {
this._var ??= {}
this._var[key as string] = value
// @ts-expect-error this._var is initialized as {}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It throws a type error that points to the possibility of undefined. But it has been initialized above. So ignore it.

this._var[key] = value
}

/**
Expand All @@ -498,7 +498,8 @@ export class Context<
* ```
*/
get: Get<E> = (key: string) => {
return this._var ? this._var[key] : undefined
// @ts-expect-error this._var is initialized as {}
return this._var[key]
}

/**
Expand Down