I have the following function to test:
export const createContext = async (context: any) => {
const authContext = await AuthGQL(context)
console.log(authContext)
if(authContext.isAuth === false) throw 'UNAUTHORIZED'
return authContext
}
I am trying to test the above function via:
describe('Testing Apollo service file', () => {
beforeAll(async () => {
await mongoConnect()
})
test('test apollo context setup and configuration', () => {
const mockContext = {
req: {
headers: {
}
}
} as ExpressContext
expect(() => createContext(mockContext)).toThrow()
})
afterAll(async () => {
await mongoDisconnect()
})
})
where my beforeAll
afterAll
calls are just connecting/disconnecting from the local database that will be used for data purposes. I am passing in mockContext
which normally will have more to it but for the sake of testing is fine and intentionally has missing fields to ensure the createContext
throws 'UNAUTHORIZED'
Here is the terminal output for the test:
UPDATED
Per Jest documentation and doing more testing: https://jestjs.io/docs/using-matchers I wrote another function that throws an error and tested via the following line:
// test sync function
function compileAndroidCode() {
throw new Error('UNAUTHORIZED');
}
// Expect function that tests the thrown error
expect(() => compileAndroidCode()).toThrow('UNAUTHORIZED')
So I seem to be messing something up in the async/await syntax with the test.
CodePudding user response:
You have an async
function, so you need to await
it. Try it like this:
test('test apollo context setup and configuration',async () => {
const mockContext = {
req: {
headers: {
}
}
} as ExpressContext
await expect(createContext(mockContext)).rejects.toThrow()
})