Reputation: 786
Hi im trying to create tests for my code and i got a problem, the main message on terminal is:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest).
{import * as strtok3 from 'strtok3';
^^^^^^
SyntaxError: Cannot use import statement outside a module
looks that one of my dependencies is unable to work with jest, maybe cause im using typescript. Someone knows how can i fix that? I let all necessary info about my project, including the error on terminal, above. Thank you.
File that im testing:
import {
S3Client,
PutObjectCommand,
PutObjectCommandInput,
} from "@aws-sdk/client-s3";
import { v4 as uuidv4 } from "uuid";
import { fileTypeFromBuffer } from "file-type";
import { MulterFile } from "../../../types/MulterFile";
import { createImageInDB } from "../create-in-db";
const client = new S3Client({
region: "sa-east-1",
credentials: {
accessKeyId: process.env.AWS_IAM_IMAGES_ACCESS_KEY!,
secretAccessKey: process.env.AWS_IAM_IMAGES_SECRET_KEY!,
},
});
// export const UploadFileSchema = z.object({
// file: z.instanceof(),
// });
// export type UploadFileType = z.infer<typeof UploadFileSchema>;
export const verifyFileTypeIsCorrect = async (
types: string[],
file: MulterFile
) => {
const fileType = await fileTypeFromBuffer(file.buffer);
if (!fileType) {
return false;
}
if (types.includes(fileType.ext)) {
return `.${fileType.ext}`;
}
return false;
};
const acceptedFileTypes = ["jpeg", "png", "jpg", "webp"];
export const uploadImage = async ({
file,
path,
userId,
}: {
file: MulterFile;
path: string;
userId?: string | null;
}) => {
const fileType = await verifyFileTypeIsCorrect(acceptedFileTypes, file);
if (!fileType) {
return {
success: false,
message: `Tipo de arquivo inválido, aceitamos apenas: ${acceptedFileTypes.join(
", "
)}`,
};
}
const newFileName =
`${path}/${userId ? userId + "/" : ""}` + uuidv4() + fileType;
const uploadParams: PutObjectCommandInput = {
Bucket: process.env.AWS_IAM_IMAGES_BUCKET_NAME!,
Key: newFileName,
Body: file.buffer,
};
let output;
try {
output = await client.send(new PutObjectCommand(uploadParams));
} catch (error) {
return {
success: false,
message: "Erro ao fazer upload da imagem.",
};
}
const url = `https://${process.env.AWS_IAM_IMAGES_BUCKET_NAME}.s3.sa-east-1.amazonaws.com/${newFileName}`;
return {
success: true,
message: "Upload feito com sucesso.",
data: {
url,
},
};
};
export const uploadImageAndCreateInDB = async ({
file,
path,
userId,
alt,
name,
}: {
file: MulterFile;
path: string;
userId: string;
alt?: string;
name?: string;
}) => {
const {
data: dataUpload,
message: messageUpload,
success: successUpload,
} = await uploadImage({ file, path, userId });
if (!successUpload || !dataUpload) {
throw new Error(messageUpload);
}
const { data, message, success } = await createImageInDB({
url: dataUpload.url,
alt,
userId,
name,
});
if (!success || !data) {
throw new Error(message);
}
return {
success: true,
message: "Upload feito com sucesso.",
data,
};
};
jest.config.js
module.exports = {
clearMocks: true,
preset: "ts-jest",
testEnvironment: "node",
setupFilesAfterEnv: ["./singleton.ts"],
};
package.json
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"postinstall": "prisma generate",
"test": "NODE_ENV=test jest -i --verbose"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.238.0",
"@bmunozg/react-image-area": "^1.1.0",
"@headlessui/react": "^1.7.7",
"@heroicons/react": "^2.0.13",
"@next-auth/prisma-adapter": "^1.0.5",
"@nivo/bar": "^0.80.0",
"@nivo/core": "^0.80.0",
"@nivo/line": "^0.80.0",
"@prisma/client": "^4.8.0",
"@sendgrid/mail": "^7.7.0",
"@stripe/stripe-js": "^1.46.0",
"@tanstack/react-query": "^4.20.4",
"@trpc/client": "^10.7.0",
"@trpc/next": "^10.7.0",
"@trpc/react-query": "^10.7.0",
"@trpc/server": "^10.7.0",
"@types/node": "18.11.9",
"@types/react": "18.0.25",
"bcrypt": "^5.1.0",
"blaze-slider": "^1.9.0",
"cookies": "^0.8.0",
"daisyui": "^2.46.0",
"eslint": "8.27.0",
"eslint-config-next": "^13.1.1",
"file-type": "^18.0.0",
"jsonwebtoken": "^9.0.0",
"lodash": "^4.17.21",
"micro": "^9.4.1",
"micro-cors": "^0.1.1",
"multer": "^1.4.5-lts.1",
"next": "^13.1.1",
"next-auth": "^4.18.7",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-toastify": "^9.1.1",
"sanitize-html": "^2.8.1",
"stripe": "^11.5.0",
"uuid": "^9.0.0",
"zod": "^3.20.2"
},
"devDependencies": {
"@tailwindcss/typography": "^0.5.8",
"@types/bcrypt": "^5.0.0",
"@types/cookies": "^0.7.7",
"@types/jest": "^29.2.4",
"@types/jsonwebtoken": "^8.5.9",
"@types/lodash": "^4.14.191",
"@types/micro-cors": "^0.1.2",
"@types/multer": "^1.4.7",
"@types/react-dom": "^18.0.10",
"@types/sanitize-html": "^2.8.0",
"@types/uuid": "^8.3.4",
"autoprefixer": "^10.4.13",
"jest": "^29.3.1",
"jest-mock-extended": "^3.0.1",
"postcss": "^8.4.20",
"prisma": "^4.8.0",
"tailwindcss": "^3.2.4",
"ts-jest": "^29.0.3",
"typescript": "^4.9.4"
}
index.test.ts file:
import {
uploadImage,
verifyFileTypeIsCorrect,
} from "../../../src/lib/services/image/upload";
import { OBJECT_TO_MOCK_USER } from "../auth/index.test";
export const OBJECT_TO_MOCK_IMAGE = () => ({
id: "clbfokijd00007z6bsf3qgq5t",
url: `https://${process.env.AWS_IAM_IMAGES_BUCKET_NAME}.s3.sa-east-1.amazonaws.com/texts/clbfp20sl00097z6bnuptsu8f/b49afd22-337b-43e9-811c-d70c551c4086.jpg`,
name: "Teste Nome",
});
jest.mock("@aws-sdk/client-s3", () => {
return {
S3Client: jest.fn(() => ({
send: jest.fn(() => ({
success: true,
message: "Upload feito com sucesso.",
data: {
url: `https://${process.env.AWS_IAM_IMAGES_BUCKET_NAME}.s3.sa-east-1.amazonaws.com/texts/clbfp20sl00097z6bnuptsu8f/b49afd22-337b-43e9-811c-d70c551c4086.jpg`,
},
})),
})),
};
});
jest.mock("uuid", () => {
return {
v4: jest.fn(() => "b49afd22-337b-43e9-811c-d70c551c4086"),
};
});
describe("Image", () => {
let image: any;
let user: any;
beforeEach(async () => {
image = OBJECT_TO_MOCK_IMAGE();
user = OBJECT_TO_MOCK_USER("123456789");
});
test("deve verificar se os tipos do arquivo são válidos", async () => {
const file = {
mimetype: "application/pdf",
buffer: Buffer.from(""),
originalname: "teste.pdf",
};
const acceptedFileTypes = ["jpeg", "png", "jpg", "webp"];
await expect(
verifyFileTypeIsCorrect(acceptedFileTypes, file)
).resolves.toEqual({
success: false,
message: `Tipo de arquivo inválido, aceitamos apenas: ${acceptedFileTypes.join(
", "
)}`,
});
});
test("verify uploadImage function que deve fazer upload de uma imagem", async () => {
const file = {
mimetype: "image/jpeg",
buffer: Buffer.from(""),
originalname: "teste.jpeg",
};
await expect(
uploadImage({
file,
path: "teste",
userId: user.id,
})
).resolves.toEqual({
success: true,
message: "Upload feito com sucesso.",
data: {
url: `https://${process.env.AWS_IAM_IMAGES_BUCKET_NAME}.s3.sa-east-1.amazonaws.com/teste/${user.id}/b49afd22-337b-43e9-811c-d70c551c4086.jpg`,
},
});
});
});
Console Error:
FAIL tests/api/image/index.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/test/Dev/next/node_modules/file-type/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as strtok3 from 'strtok3';
^^^^^^
SyntaxError: Cannot use import statement outside a module
5 | } from "@aws-sdk/client-s3";
6 | import { v4 as uuidv4 } from "uuid";
> 7 | import { fileTypeFromBuffer } from "file-type";
| ^
8 | import { MulterFile } from "../../../types/MulterFile";
9 | import { createImageInDB } from "../create-in-db";
10 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1449:14)
at Object.<anonymous> (src/lib/services/image/upload/index.ts:7:1)
at Object.<anonymous> (tests/api/image/index.test.ts:4:1)
Upvotes: 5
Views: 1913
Reputation: 891
strtok3 is an ECMAScript modules (ESM). In a CommonJS (CJS) project (it looks like that is what you have) can use dynamic import to load an ESM module.
(async () => {
const strtok3 = await import('strtok3');
})();
I will demonstrate how to do that. I use URLs instead of module names here, as I cannot import from local installed dependencies.
const strtok3 = 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
const token_types = 'https://cdn.jsdelivr.net/npm/[email protected]/+esm';
async function run() {
const {fromBuffer} = await import(strtok3);
const {UINT32_BE} = await import(token_types);
const testData = new Uint8Array([0x01, 0x00, 0x00, 0x00]);
const tokenizer = fromBuffer(testData);
const number = await tokenizer.readToken(UINT32_BE);
console.log(`Decoded number = ${number}`);
}
run().catch(err => {
console.error(`An error occured: ${err.message}`);
})
But you are using TypeScript, and gives additional challenge, as the TypeScript compiler does not respect the dynamic import, in CJS project.
import {loadEsm} from 'load-esm';
(async () => {
const strtok3 = await loadEsm<typeof import('strtok3')>('strtok3');
})();
I used strtok3 (which was the error), but the same applies to file-type module.
As per StackOverflow policies I need disclose that I am the owner of all the used dependencies: strtok3, token-types, load-esm, and I am contributor of file-type.
But rather then get this to work in your CJS project, it better to migrate your project to ESM. In your ESM project, you more easily load both ESM and CJS dependencies.
Upvotes: 0