You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi im trying to create tests for my code in NextJs with typescript 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.
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)
When i try set "type": "module" i get this error:
ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/Users/teste/Dev/next/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///Users/teste/Dev/next/jest.config.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
at async requireOrImportModule (/Users/teste/Dev/next/node_modules/jest-util/build/requireOrImportModule.js:55:32)
at async readConfigFileAndSetRootDir (/Users/teste/Dev/next/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:112:22)
at async readInitialOptions (/Users/teste/Dev/next/node_modules/jest-config/build/index.js:396:13)
at async readConfig (/Users/teste/Dev/next/node_modules/jest-config/build/index.js:147:48)
at async readConfigs (/Users/teste/Dev/next/node_modules/jest-config/build/index.js:417:26)
The text was updated successfully, but these errors were encountered:
Hi im trying to create tests for my code in
NextJs
withtypescript
and i got a problem, the main message on terminal is: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:
jest.config.js
package.json
index.test.ts file:
Console Error:
When i try set
"type": "module"
i get this error:The text was updated successfully, but these errors were encountered: