One of the functions I'm testing is shown below:
export const createContext = async (context: any) => {
const authContext = await AuthGQL(context)
console.log(authContext)
if(authContext.isAuth === false) throw 'UNAUTHORIZED'
return authContext
}
I am currently testing this function as follows:
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()
})
})
The beforeAll
and afterAll
calls are simply connecting and disconnecting from a local database for testing purposes. The mockContext
being passed intentionally has missing fields to trigger an 'UNAUTHORIZED' error in the createContext
function.
After running the test, the terminal output is as follows:
https://i.sstatic.net/XB4t5.png
UPDATE:
In accordance with Jest documentation and further testing: https://jestjs.io/docs/using-matchers, I wrote another function that throws an error and tested it using the following line:
// test sync function
function compileAndroidCode() {
throw new Error('UNAUTHORIZED');
}
// Expect function that tests the thrown error
expect(() => compileAndroidCode()).toThrow('UNAUTHORIZED')
It seems there might be some syntax issues related to the async/await functionality in my test.