Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jest error while trying to use with the file-type module. How can I fix "Cannot use import statement outside a module"? #565

Closed
HenriqueRamos13 opened this issue Dec 26, 2022 · 4 comments

Comments

@HenriqueRamos13
Copy link

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.

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)

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)
@sindresorhus
Copy link
Owner

This is not a problem with this package. Try asking on the Jest issue tracker instead.

@sindresorhus
Copy link
Owner

• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.

@sindresorhus sindresorhus closed this as not planned Won't fix, can't repro, duplicate, stale Dec 26, 2022
@vladnec
Copy link

vladnec commented Feb 16, 2023

@HenriqueRamos13 have you found a solution?

@HeriYantodotDev
Copy link

I encountered the same issue. Does anyone find the workaround?
@vladnec @sindresorhus @HenriqueRamos13

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants