I didn’t really run my tests as I changed my application, and now have and one broken. I fixed the others so far.
What is happening?
I am running a scenario where I am “updating a user” however on the updateUser
function if I have a requireOwnership
function before like so.
api/src/services/users/users.ts
export const updateUser: MutationResolvers['updateUser'] = async ({
id,
input,
}) => {
await requireOwnership(id)
return db.user.update({
data: input,
where: { id },
})
}
That requireOwnership function looks like the following
api/src/lib/owner.ts
import { ForbiddenError } from '@redwoodjs/graphql-server'
import { db } from 'src/lib/db'
export const requireOwnership = async (id) => {
const user = await db.user.findUnique({
where: { id: id },
})
console.log(context)
const uuid = context.currentUser.user.uuid
if (context.currentUser.roles[0] === 'ADMIN') {
return
}
if (!user || user.uuid !== uuid) {
throw new ForbiddenError("You don't own this resource.")
}
}
The problem I am having is the context is not being set. What I attempted to do was use setContext
in my test.
api/src/services/users/users.test.ts
import { setContext } from '@redwoodjs/graphql-server'
const MOCKED_USER = {
user: {id:123, uuid: 'String3757979', email: 'String1761590'}
}
setContext({
currentUser: MOCKED_USER,
})
describe('users', () => {
scenario('updates a user', async (scenario: StandardScenario) => {
const original = await user({ id: scenario.user.one.id })
const result = await updateUser({
id: original.id,
input: { uuid: 'String52764902' },
})
expect(result.uuid).toEqual('String52764902')
})
})
The error I get is that
TypeError: Cannot read properties of undefined (reading 'user')
9 | console.log(context)
10 |
> 11 | const uuid = context.currentUser.user.uuid
| ^
12 |
13 | if (context.currentUser.roles[0] === 'ADMIN') {
14 | return
However since I am console logging the context. I do get the object below. So I am stumped as to why as soon as the context variable is met in the code it fails to traverse to the user object it thinks it’s undefined.
console.log
{
currentUser: { user: { id: 123, uuid: 'String3757979', email: 'String1761590' } }
}
Any help would be appreciated greatly. Thanks