How to use a dynamic import in a firebase cloud function using Javascript - node.js

How can I make this work without having the pre-deploy linter produce an error? If I disable the linter will it work on the cloud? (It works with my mocha tests).
async function() {
const { ChatGPTAPI } = await import('chatgpt');
}
29:32 error Parsing error: Unexpected token import
✖ 1 problem (1 error, 0 warnings)
Setting type: "module" in package.json produces error with the eslintrc.js

Related

How do I run unit tests on Svelte component logic while also importing an environment variable?

I am trying to run Jest unit tests on function logic that is imported from a Svelte component. The program runs fine except when I try to import into Jest: I can console log the env variable in the line below ok.
The problem is that this line gives me an error when i try to run the unit test, I guess because its trying to import the file into the jest test. It runs fine when the program is actually running, but when the Jest test tries to import it, the context changes or ... something. Anyway, here's the line, from my file src/routes/signup/index.svelte:
// in the script tag of a svelte component
<script context="module">
const googleRecaptchaSiteKey =
typeof import.meta.env.VITE_GOOGLE_RECAPTCHA_KEY === "string"
? import.meta.env.VITE_GOOGLE_RECAPTCHA_KEY
: ""
export function foo() {
// ...
}
</script>
This code must run in my Jest test because it gives the error when I run npm test, so here's how I am executing that code:
import { foo } from "../src/routes/signup/index.svelte"
// It must execute the whole component when I import from it?
describe("signup page logic", () => {
test("ensure that the signup form button enablement conditions work properly", () => {
const failureOne = foo()
}
}
The error message itself:
/home/rlm/Code/projName/src/routes/signup/index.svelte:446
const googleRecaptchaSiteKey = typeof import.meta.env.VITE_GOOGLE_RECAPTCHA_KEY === "string"
^^^^
SyntaxError: Cannot use 'import.meta' outside a module
> 1 | import { updateEnabledSubmitSignup } from "../src/routes/signup/index.svelte"
Now since writing the above text, I have been adventuring for approx 27 minutes to discover a solution. What I have done is try to follow guides.
Per the instruction of Environment variables with SvelteKit I did:
in src/lib/variables.ts:
export const variables = {
foo: import.meta.env.VITE_FOO,
secondRecaptchaKey: import.meta.env.VITE_SECOND_RECAPTCHA_KEY,
}
And then I import it into the Svelte file: import { variables } from "../../lib/variables"
I run npm run dev and it console logs the value fine.
But then when I run npm test I get:
src/lib/variables.ts:3:23 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.
3 secondRecaptchaKey: import.meta.env.VITE_SECOND_RECAPTCHA_KEY,
TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'
Test suite failed to run import.meta.env.VITE_* does also but I tried to follow it and it fails even after installing vite-plugin-environment and babel-plugin-transform-import-meta and adding them to the babel plugins:
export const variables = { // logs with all values undefined
foo: process.env.VITE_FOO,
secondRecaptchaKey: process.env.VITE_SECOND_RECAPTCHA_KEY,
}
TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system' also has advice that fails for me, or i have done it wrong. In my current state npm test logs the env variables as undefined.
edit: For anyone in the future who has this problem, I was able to go around the problem by doing this totally-good-enough workaround:
jest.mock("../src/lib/envVariables", () => ({
envVariables: { foo: "bar", secondRecaptchaKey: "someMockValue" },
}))
I credit nstanard in this post for saving us from the hassle

Using serverless deployment to lambda with ES6 /Node.js v16

Newbie question....
I have a locally working node.js application which I am now trying to deploy express to AWS lambda. I have used this guide to deploy a test version (which worked).
I now am trying to implement my application which uses ES6 (and has type: module in package.json).
In my application I have added
import serverless from 'serverless-http'
but I cannot figure out the appropriate syntax for the export - the original was...
module.exports.handler = serverless(app);
I have tried:
const handler = async (app) =\> {
return serverless(app)
}
export default handler
Error message received:
2022-11-05T15:50:25.962Z undefined ERROR Uncaught Exception
"errorType": "Runtime.HandlerNotFound",
"errorMessage": "app.handler is undefined or not exported",
"stack": [
"Runtime.HandlerNotFound: app.handler is undefined or not exported",
" at Object.UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:979:15)",
" at async start (file:///var/runtime/index.mjs:1137:23)",
" at async file:///var/runtime/index.mjs:1143:1"
]
I strongly suspect I am missing some fundamental understanding - truly appreciate some guidance.
The reason for the error is that you are sending a default export when AWS Lambda is expecting a named export.
The issue is the same as with all ES6 imports/exports:
// export.js
export default const defaultExport = "foo"
export const namedExport = "bar"
// import.js
import { defaultExport } from "./export.js" // error, cannot find defaultExport
import { namedExport } from "./export.js" // success, found namedExport
import defaultExport from "./export.js" // success, found defaultExport
So, it's like the case above where you're sending the defaultExport, but AWS Lambda wants the { namedExport }. You just need to remove default from your export, and make sure you're building the handler properly. Here is a suggestion to do that:
const lambda = serverless(app)
export async function handler(event, context) {
return lambda(event, context)
}
I've tested and it's working with serverless-offline using Node18.x. You can read more about exports on MDN.

Unexpected reserved word 'yield' when running Jest unit tests

I'm using TypeScript and Jest to write unit tests. When I tried to run them, I got the following error messages:
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.
SyntaxError: C:\..\my\file\name.web.spec.ts: Unexpected reserved word 'yield'.
This came from an original TypeScript section like the following:
it("should do things right", () => {
const payload = { ... };
await manager.init(payload);
});
The solution seems obvious in retrospect when looking at the code, but easy to miss. I just simply needed to make the function async.
it("should do things right", async () => {
const payload = { ... };
await manager.init(payload);
});

uuid is not a function while using jest

I have the following setup:
// uuid-wrapper.ts
import { v4 as uuidV4 } from 'uuid';
const uuid: () => string = uuidV4;
export { uuid };
// uuid-wrapper.spec.ts
import { uuid } from './uuid-wrapper';
describe('uuid-wrapper', () => {
console.log(uuid());
});
This works fine runtime, but it breaks in test. I'm trying to migrate to Jest 29 and I'm getting the following error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
From uuid's repo I found a workaround which, after applied and my jest.config.js looks like this:
module.exports = {
moduleNameMapper: {
uuid: require.resolve("uuid"),
},
};
This gives me a different error but I still have no idea what it means:
> jest uuid-wrapper --no-coverage
FAIL src/uuid-wrapper/uuid-wrapper.spec.ts
● Test suite failed to run
TypeError: (0 , uuid_wrapper_1.uuid) is not a function
In fact, any function I export from this file (uuid-wrapper.ts) is not resolved. I have other tests that follow a similar pattern of reexporting packages but only this one breaks. I'm using uuid 9.0.0 and jest 29.1.2.
Edit: After a bit more testing, it turns out that anything I import into the test is "not a function".
uuid ships as an ESModule and Jest should not need to transform it. Add it to your transformIgnorePatterns in your Jest config:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(uuid))'],
}
Edit: After a bit more testing, it turns out that anything I import into the test is "not a function".
I had very similar symptoms once: builds and works as excepted, yet ...is not function in jest. The culprit was a circular dependency I accidentally introduced with my story. Maybe check for that.
As I suspected, the issue was in the naming. Renaming the files and directory to just wrapper solved the issue.

Cypress: Cannot use cy.task() to load dataset to Mongo before tests

I'm trying to use cy.taks() to load certain datasets to mongo before a test is run. But I'm getting errors. I've got a module where I export 2 functions, one from dropping a collection, and the other to load an object to a collection. Here is my cypress/plugins/index.js:
module.exports = (on, config) => {
on("task", {
"defaults:db": () => {
const {dropCollection, createUser } = require("../../lib/connectDB");
dropCollection("users");
createUser(userData)
},
});
};
Here is my /lib/connecDB.js:
export function dropCollection(collection) {
return mongoose.connection.dropCollection(collection);
}
export async function createUserInDB(userData) {
await User.create(userData);
}
So when I run the test, I'm getting:
cy.task('defaults:db') failed with the following error:
Unexpected token 'export'
Tried as well importing these function outside the index.js export, but getting same result.
I'd say it is something about export/import. The functions are exported as ES6, and imported as ES5.
I've tried to import the function the ES6 like:
import { dropCollection, createUser } from '../lib/connectDB'
And then export the plugin function also as ES6, but then I get:
Error: The plugins file is missing or invalid.
Your `pluginsFile` is set to `C:\Users\someRoute\cypress\plugins\index.js`, but either the file is missing, it contains a syntax error, or threw an error when required. The `pluginsFile` must be a `.js`, `.ts`, or `.coffee` file.
I've also tried to import required modules outside the function like:
const globalDbUtils = require('../lib/connectDB')
And then use the functions as
globalDbUtils.dropCollection("collectionName")
globalDbUtils.createUser(userData)
But I'm getting last error. I've tried pretty much everything, I tried to import Mongoose models straight, mongo client etc...Also I tried to import just one function and return it (just copy/pasting official doc...) but cannot make it work. I researched for a couple of days getting nothing, I found there is a npm package that helps u doing this, but since cypress allows you to do this by using no more plugins, I'd like to do it with no more tools than cypress itself.
Anyone knows what I am doing wrong?
Thanks in advance!
You need to use require instead of import at the top of your file and when exporting at the bottom use
module.exports = { createUserInDB }
Instead of exporting as you are currently doing.

Resources