Next.js Discord

Discord Forum

jest TypeError: payload must be an instance of Uint8Array

Unanswered
Bald Eagle posted this in #help-forum
Open in Discord
Bald EagleOP
When running jest that calls the below function in a test I get TypeError: payload must be an instance of Uint8Array. The code runs fine normally in node. I have tried multiple different versions of jest, and jose to no avail. The test environment is jest-environment-jsdom. I cannot find any info about this online whatsoever.

import { SignJWT, jwtVerify, JWTVerifyOptions, JWTPayload } from 'jose'; //used for jwt
export async function get_jwt_token(
    user_id: string,
) {
    const sig = (new TextEncoder().encode('MYSECRETKEY543534')) as Uint8Array;
    const token = await new SignJWT()
        .sign(sig); //causes TypeError: payload must be an instance of Uint8Array in jest

    return token;
}

    it('get_jwt_token should not cause an error', async () => {
        const token = await get_jwt_token('admin', 'my-password');
        console.log(token);
    });


Any help would be appreciated.

1 Reply

Bald EagleOP
Forgot to mention I also get a related error when calling jwtVerify Key for the HS256 algorithm must be one of type KeyObject or Uint8Array. Received an instance of Uint8Array

 try {
        const result = await jwtVerify(
            token,
            new TextEncoder().encode(get_jwt_secret_key()),
            {
                algorithms: ['HS256'],
                maxTokenAge: '10 m',
            } as JWTVerifyOptions
        );
        return result.payload as unknown as UserJwtPayload;
    } catch (err) {
        throw new Error(getErrorMessage(err));
    }