Lex*_*Lex 9 node.js jwt graphql apollo-server
How do we pass headers to Apollo server executeOperation in tests?
There is mention about passing a headers object here
I'm trying to pass an auth header with or without a JWT token to test access control.
const result = await server.executeOperation({ query: query, http: { headers: { authorization: "" } } })
// Type '{ authorization: string; }' is not assignable to type 'Headers'.
// Object literal may only specify known properties, and 'authorization' does not exist in type 'Headers'.ts(2322)
Run Code Online (Sandbox Code Playgroud)
This results in a type error. There is a Headers class defined in the Apollo server types in fetch.d.ts but I'm un able to import to instantiate it.
Using "apollo-server": "^2.25.2". Any hints or links to get this going?
Update: as a work around I'm decrypting and decoding the JWT in the server context and passing an authenticated user around in there. Then I'm able to mock the whole context and create a new test server with the mocked context. It'd be nice to be able to user headers for more production like experience but this works for now.
import { mockDeep, mockReset } from 'jest-mock-extended'
interface Context {
prisma: PrismaClient
user: () => User|null
}
export const context = mockDeep<Context>()
export const testServer = new ApolloServer({
typeDefs,
resolvers,
context
});
// ...
context.user.mockReturnValue({
id: 1,
name: "Foo",
slug: "foo",
})
const res = await testServer.executeOperation({ query: query })
Run Code Online (Sandbox Code Playgroud)
小智 3
Apollo Server 现在支持executeOperation 的第二个参数。可以提供上下文函数中使用的参数。
const result = await server.executeOperation(
{ query: query },
{ req: { headers: { authorization: '...' } } }
);
Run Code Online (Sandbox Code Playgroud)
注意:使用 Typescript,它会抱怨,但您可以将其转换为任何类型并避免构建整个express.Request类型。
使用 apollo-server-core@3.5.0 进行测试
另一种解决方案有效,但我发现这个很方便。如果您模拟令牌解析,则可以轻松模拟来自不同用户的调用。
| 归档时间: |
|
| 查看次数: |
1641 次 |
| 最近记录: |