How to setup clipboardy in cypress 10? - javascript

I'm pretty new to cypress. I tried to install clipboardy to one of my project.
But the guide that I found online like this mostly setup on the older cypress which is using the plugins/index.js file.
I tried something like this and got error
const { defineConfig } = require("cypress");
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin =
require("#badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
require("#badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;
const clipboardy = require("clipboardy");
module.exports = defineConfig({
e2e: {
async setupNodeEvents(on, config) {
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});
on("file:preprocessor", bundler);
await addCucumberPreprocessorPlugin(on, config);
on('task', {
getClipboard () {
return clipboardy.readSync();
}
});
return config;
},
specPattern: "cypress/e2e/features/*.feature",
baseUrl: "XXXXXXXXXXXXX",
chromeWebSecurity: false,
},
});
The error
Error screen
Stack Trace
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\node_modules\clipboardy\index.js from C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js not supported.
Instead change the require of index.js in C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js to a dynamic import() which is available in all CommonJS modules.
at Object. (C:\Users\XXXXXXXXXXXXXXXXXXXXXXX\cypress.config.js:8:20)
at async Promise.all (index 0)
at async loadFile (C:\Users\XXXX\AppData\Local\Cypress\Cache\10.4.0\Cypress\resources\app\node_modules\#packages\server\lib\plugins\child\run_require_async_child.js:106:14)
at async EventEmitter. (C:\Users\XXXX\AppData\Local\Cypress\Cache\10.4.0\Cypress\resources\app\node_modules\#packages\server\lib\plugins\child\run_require_async_child.js:116:32)

It's because the clipboardy package has type: "module" in it's 'package.json'.
This tells anything that uses the package that you should use import not require to load the package.
Use dynamic imports, as hinted in the error message
Instead change the require of index.js in ... to a dynamic import()
const clipboard = import('clipboardy')

Related

I am getting a required error using graphql tools

I am building a gql server application using apollo server.
When I try to load my .graphql files using import { loadFilesSync } from '#graphql-tools/load-files', this works very well, but when I load my resolver files, i get an error
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /userpath/index.js from /userpath/server-gql/noop.js not supported.
Instead change the require of index.js in /userpath/server-gql/noop.js to a dynamic import() which is available in all CommonJS modules.
at Object.newLoader [as .js] (/userpath/server-gql/node_modules/pirates/lib/index.js:141:7)
at file:///userpath/server-gql/node_modules/#graphql-tools/load-files/esm/index.js:104:33
at Array.map (<anonymous>)
at loadFilesSync (file:///userpath/server-gql/node_modules/#graphql-tools/load-files/esm/index.js:95:10)
at file:///userpath/server-gql/schema.js:20:24
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
I am using "type": "module" in my package.json.
Here's my code snippet for where i get the error
import path from 'path'
import { fileURLToPath } from 'url'
import { loadFilesSync } from '#graphql-tools/load-files'
import { mergeTypeDefs, mergeResolvers } from '#graphql-tools/merge'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const typesArray = loadFilesSync(path.join(__dirname, '.'), {
recursive: true,
extensions: ['graphql'],
})
const resolversArray = loadFilesSync(path.join(__dirname, './graphql/**/*.resolvers.js'), {
recursive: true,
extensions: ['js'],
})
const newResolversArray = resolversArray.slice(1)
export const typeDefs = mergeTypeDefs(typesArray)
export const resolvers = mergeResolvers(newResolversArray)
I think the error occurs in the resolvers array.
I was running into a very similar issue and found this workaround/solution worked for me: https://github.com/ardatan/graphql-tools/issues/1750#issuecomment-655828240
I had to modify that answer a bit to get it working in my codebase...below is what my own resolverFiles snippet now looks like (I'm not 100% sure what your import/naming conventions look like, or I'd try to apply this to your code snippet).
I have a mixed, nested directory schema/ that contains resolver files of the format SomethingResolvers.ts. Each of these look like the following (I'm using codegen):
import { Resolvers } from "../../generated/graphql";
export const resolvers: Resolvers = { /* resolver implementations */ };
const resolverFiles = await loadFiles(
path.join(__dirname, "**/*Resolvers.js"),
{
requireMethod: async (path) => {
const module = await import(pathToFileURL(path).toString());
return module["resolvers"];
},
recursive: true,
}
);

Module "util" has been externalized for browser compatibility. Cannot access "util.promisify" in client code

I am trying to scrap linkeidn profile using this library:
https://www.npmjs.com/package/#n-h-n/linkedin-profile-scraper.
this is my code:
<script>
import { LinkedInProfileScraper } from '#matidiaz/linkedin-profile-scraper';
import { onMount } from 'svelte';
import { session } from '$app/stores';
onMount(async () => {
const token = session?.provider_token;
console.log(token);
const scraper = new LinkedInProfileScraper({
sessionCookieValue: token,
keepAlive: false
});
// Prepare the scraper
// Loading it in memory
await scraper.setup();
const result = await scraper.run('https://www.linkedin.com/in/jvandenaardweg/');
console.log(result);
});
</script>
I am using sveltekit to get the information, can someone point out how to solve this prb,I am not finding much information online.
Hi what worked for me was to fix the vite.config.ts into something like this:
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: "util/",
'#': path.resolve(__dirname, './src'),
}
}
where we actually resolve the alias of util and add to it 'util/'
npm i util,
however this lib continues giving errors so I removed it.

Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/got/dist/source/index.js from /app/commands/Image/meme.js not supported

Code:
const { EmbedBuilder } = require("discord.js");
const got = require("got");
module.exports = {
name: "meme",
description: "Shows an image of a meme!",
run: async (client, message, args) => {
got("https://www.reddit.com/r/memes/random/.json").then(response => {
const [list] = JSON.parse(response.body);
const [post] = list.data.children;
const permalink = post.data.permalink;
const memeUrl = `https://reddit.com${post.data.permalink}`;
const memeImage = post.data.url;
const memeTitle = post.data.title;
const memeUpvotes = post.data.ups;
const memeNumComments = post.data.num_comments;
const memeEmbed = new EmbedBuilder()
.setTitle(`${memeTitle}`)
.setURL(`${memeUrl}`)
.setColor("Random")
.setImage(memeImage)
.setFooter({ text: `👍 ${memeUpvotes} | 💬 ${memeNumComments}` });
message.reply({ embeds: [memeEmbed] });
});
}
};
Error:
const got = require("got");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module
/app/node_modules/got/dist/source/index.js from /app/commands/Image/meme.js not supported.
I’m not too sure what this ESM is, I’ve never dealt with it before, therefore I don’t know what to do to fix this.
Kinda think it’s got to do something with the package itself, but like I said I’m clueless as I’ve never had this error before.
got is a native ESM and no longer provides a CommonJS export.
Use ESM
To use the latest version, you'll have to convert to ESM:
you need to add "type": "module" to your package.json
replace all require()s and module.exports with import and export
Downgrade got
Another option is to downgrade got to v11.8.3 as it's pretty stable:
You can run npm i got#11.8.3 in your console.

How do I use HTTP urls with Node ESM module loader?

I have the following import mongo from "mongodb"; I would like to avoid using npm and instead use unpkg.com like this import mongo from "https://unpkg.com/mongodb";. However, when I run I get...
...#penguin:~/...$ node --harmony test.mjs node:internal/process/esm_loader:74
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. Received protocol 'https:'
at new NodeError (node:internal/errors:328:5)
at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:825:11)
at Loader.resolve (node:internal/modules/esm/loader:86:40)
at Loader.getModuleJob (node:internal/modules/esm/loader:230:28)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:56:40)
at link (node:internal/modules/esm/module_job:55:36) {
code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}
Because it uses the term default module loader I was wondering if there was an alternative ESM loader I could use.
Node will eventually support ESM URL imports. This feature is currently available under a CLI flag --experimental-network-imports. It doesn't ship with public releases yet (as of Node 18.0.0), so you will need to build Node from source for this as of current. See https://nodejs.org/api/esm.html#https-and-http-imports
In the meanwhile, Node has experimental support for module loaders and even shows a HTTPS loader as an example. See https://nodejs.org/api/esm.html#esm_https_loader
// https-loader.mjs
import { get } from 'https';
export function resolve(specifier, context, defaultResolve) {
const { parentURL = null } = context;
// Normally Node.js would error on specifiers starting with 'https://', so
// this hook intercepts them and converts them into absolute URLs to be
// passed along to the later hooks below.
if (specifier.startsWith('https://')) {
return {
url: specifier
};
} else if (parentURL && parentURL.startsWith('https://')) {
return {
url: new URL(specifier, parentURL).href
};
}
// Let Node.js handle all other specifiers.
return defaultResolve(specifier, context, defaultResolve);
}
export function load(url, context, defaultLoad) {
// For JavaScript to be loaded over the network, we need to fetch and
// return it.
if (url.startsWith('https://')) {
return new Promise((resolve, reject) => {
get(url, (res) => {
let data = '';
res.on('data', (chunk) => data += chunk);
res.on('end', () => resolve({
// This example assumes all network-provided JavaScript is ES module
// code.
format: 'module',
source: data,
}));
}).on('error', (err) => reject(err));
});
}
// Let Node.js handle all other URLs.
return defaultLoad(url, context, defaultLoad);
}
Use like so:
node --experimental-loader ./https-loader.mjs ./main.mjs

Require not behaving as expected

I'm using the proxyquire library, which mocks packages on import.
I'm creating my own proxyquire function, which stubs a variety of packages I use regularly and want to stub regularly (meteor packages, which have a special import syntax):
// myProxyquire.js
import proxyquire from 'proxyquire';
const importsToStub = {
'meteor/meteor': { Meteor: { defer: () => {} } },
};
const myProxyquire = filePath => proxyquire(filePath, importsToStub);
export default myProxyquire;
Now I want to write a test of a file which uses one of these packages:
// src/foo.js
import { Meteor } from 'meteor/meteor'; // This import should be stubbed
export const foo = () => {
Meteor.defer(() => console.log('hi')); // This call should be stubbed
return 'bar';
};
And finally I test it like this:
// src/foo.test.js
import myProxyquire from '../myProxyquire';
// This should be looking in the `src` folder
const { foo } = myProxyquire('./foo'); // error: ENOENT: no such file
describe('foo', () => {
it("should return 'bar'", () => {
expect(foo()).to.equal('bar');
});
});
Note that my last 2 files are nested inside a subfolder src. So when I try to run this test, I get an error saying that the module ./foo couldn't be found, as it is being looked for in the "root" directory, where the myProxyquire.js file is, not the src directory as expected.
You might be able to work around that (expected) behaviour by using a module like caller-path to determine from which file myProxyquire was called, and resolving the passed path relative to that file:
'use strict'; // this line is important and should not be removed
const callerPath = require('caller-path');
const { dirname, resolve } = require('path');
module.exports.default = path => require(resolve(dirname(callerPath()), path));
However, I have no idea of this works with import (and, presumably, transpilers).

Categories

Resources