How to implement the Music Metadata Or Music MetaData Browser npm plugin in Cypress V10? - npm

I tried to implement the Node plugin in Cypress Version 10, But I couldn't done it.
https://www.npmjs.com/package/music-metadata-browser#fetchurl-function
Installation is done:
npm install --save-dev music-metadata-browser
npm install --save-dev util
Added the below lines in plugin/index.js
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
};
Added the below code in e2e/validateFile.cy.js
describe('Parsing File', () => {
it('Validating Audio File', () => {
const audioURL = 'cypress/fixtures/media/Patrikios.mp3';
console.log('url: ' + audioURL);
cy.task('validateAudioFormat', audioURL).then(data => {
const allData = Object.values(data);
console.log('All data: ' + allData);
});
/******
cy.on('validateAudioFormat', (url) => {
async () => {
const metadata = await mm.fetchFromUrl(url);
console.log('url: ' + url);
console.log(util.inspect(metadata, { showHidden: false, depth: null }));
};
});
*****/
});
});
Error:
CypressError: `cy.task('validateAudioFormat')` failed with the following error:
The task 'validateAudioFormat' was not handled in the setupNodeEvents method. The following tasks are registered: resetCoverage, combineCoverage, coverageReport
Fix this in your setupNodeEvents method here: /opt/lampp/htdocs/project/cypress.config.js
Commented block error:
taskreadAudioFiles, cypress/fixtures/media/audios/valid/Beyond_Patrick_Patrikios.mp3
CypressError
cy.task('readAudioFiles') timed out after waiting 60000ms
Anyone can help on this scenario?
Thanks!

Your project is a mixture of Cypress v9 config and Cypress v10 tests.
I presume you are on 10+ so the plugins now go in cypress.config.js
const { defineConfig } = require('cypress')
const musicMetadata = require('music-metadata-browser');
const util = require('util');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
require('#cypress/code-coverage/task')(on, config);
on('task', {
validateAudioFormat(audioTrackUrl) {
return new Promise((resolve, reject) => {
musicMetadata.parseFile(audioTrackUrl, (err, data) => {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
});
},
}
})

Related

Shopify node.js and react.js plugin with vite.js not working

I've created a plugin in shopify using node.js & vite.js.
shopify app create node
After running using npm run dev, it generates a url like this: https://b136-0000-7400-56-bc78-5000-178b-d6f3-6000.ngrok.io/login?shop=shopname.myshopify.com
When I open this link, it start reloading infinite with error
This is my index.js:
import { resolve } from "path";
import express from "express";
import cookieParser from "cookie-parser";
import { Shopify, LATEST_API_VERSION } from "#shopify/shopify-api";
import "dotenv/config";
import applyAuthMiddleware from "./middleware/auth.js";
import verifyRequest from "./middleware/verify-request.js";
const USE_ONLINE_TOKENS = true;
const TOP_LEVEL_OAUTH_COOKIE = "shopify_top_level_oauth";
const PORT = parseInt(process.env.PORT || "8081", 10);
const isTest = process.env.NODE_ENV === "test" || !!process.env.VITE_TEST_BUILD;
Shopify.Context.initialize({
API_KEY: process.env.SHOPIFY_API_KEY,
API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
SCOPES: process.env.SCOPES.split(","),
HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
API_VERSION: LATEST_API_VERSION,
IS_EMBEDDED_APP: true,
// This should be replaced with your preferred storage strategy
SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});
// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};
Shopify.Webhooks.Registry.addHandler("APP_UNINSTALLED", {
path: "/webhooks",
webhookHandler: async (topic, shop, body) => {
delete ACTIVE_SHOPIFY_SHOPS[shop];
},
});
// export for test use only
export async function createServer(
root = process.cwd(),
isProd = process.env.NODE_ENV === "production"
) {
const app = express();
app.set("top-level-oauth-cookie", TOP_LEVEL_OAUTH_COOKIE);
app.set("active-shopify-shops", ACTIVE_SHOPIFY_SHOPS);
app.set("use-online-tokens", USE_ONLINE_TOKENS);
app.use(cookieParser(Shopify.Context.API_SECRET_KEY));
applyAuthMiddleware(app);
app.post("/webhooks", async (req, res) => {
try {
await Shopify.Webhooks.Registry.process(req, res);
console.log(`Webhook processed, returned status code 200`);
} catch (error) {
console.log(`Failed to process webhook: ${error}`);
if (!res.headersSent) {
res.status(500).send(error.message);
}
}
});
app.get("/products-count", verifyRequest(app), async (req, res) => {
const session = await Shopify.Utils.loadCurrentSession(
req,
res,
app.get("use-online-tokens")
);
const { Product } = await import(
`#shopify/shopify-api/dist/rest-resources/${Shopify.Context.API_VERSION}/index.js`
);
const countData = await Product.count({ session });
res.status(200).send(countData);
});
app.post("/graphql", verifyRequest(app), async (req, res) => {
try {
const response = await Shopify.Utils.graphqlProxy(req, res);
res.status(200).send(response.body);
} catch (error) {
res.status(500).send(error.message);
}
});
app.use(express.json());
app.use((req, res, next) => {
const shop = req.query.shop;
if (Shopify.Context.IS_EMBEDDED_APP && shop) {
res.setHeader(
"Content-Security-Policy",
`frame-ancestors https://${shop} https://admin.shopify.com;`
);
} else {
res.setHeader("Content-Security-Policy", `frame-ancestors 'none';`);
}
next();
});
app.use("/*", (req, res, next) => {
const { shop } = req.query;
// Detect whether we need to reinstall the app, any request from Shopify will
// include a shop in the query parameters.
if (app.get("active-shopify-shops")[shop] === undefined && shop) {
res.redirect(`/auth?${new URLSearchParams(req.query).toString()}`);
} else {
next();
}
});
/**
* #type {import('vite').ViteDevServer}
*/
let vite;
if (!isProd) {
vite = await import("vite").then(({ createServer }) =>
createServer({
root,
logLevel: isTest ? "error" : "info",
server: {
port: PORT,
hmr: {
protocol: "ws",
host: "localhost",
port: 64999,
clientPort: 64999,
},
middlewareMode: "html",
},
})
);
app.use(vite.middlewares);
} else {
const compression = await import("compression").then(
({ default: fn }) => fn
);
const serveStatic = await import("serve-static").then(
({ default: fn }) => fn
);
const fs = await import("fs");
app.use(compression());
app.use(serveStatic(resolve("dist/client")));
app.use("/*", (req, res, next) => {
// Client-side routing will pick up on the correct route to render, so we always render the index here
res
.status(200)
.set("Content-Type", "text/html")
.send(fs.readFileSync(`${process.cwd()}/dist/client/index.html`));
});
}
return { app, vite };
}
if (!isTest) {
createServer().then(({ app }) => app.listen(PORT));
}
The app is installing fine but it's getting refreshed again and again due to failed connection to ws (as mentioned in the screenshot). I tried a few things around changing the settings of the HMR but doesn't seem to be connecting.

Jest - How to test GoogleMapsApiLoader

I am using the google map api loader for get the google map config details.
Ref: https://v2.vuejs.org/v2/cookbook/practical-use-of-scoped-slots.html#1-Create-a-component-that-initializes-our-map
I am trying to cover unit test case for this scenario.
googleMap.vue
async mounted() {
const googleMapApi = await GoogleMapsApiLoader({
apiKey: this.apiKey
})
this.google = googleMapApi
this.initializeMap()
},
googleMap.spec.js
jest.mock('google-maps-api-loader', () => {
return { ... }
});
require('google-maps-api-loader');
const wrapper = shallowMount(GoogleMap, {
propsData: {
mapConfig: {},
apiClient: 'apiclient-test-id',
apiChannel: 'apichannel-test-id'
},
mocks: {
mocksData
}
});
describe('googlemap.vue', () => {
it('should all the elements rendered', async() => {
wrapper = mountGoogleMap();
});
});
Those given line was not covering.. I am struggling to write unit test case for this file

Why is Jest running the typescript test files and then the compiled JS test files?

When I run Jest, I get 9 failing, 11 passing out of a total of 20, but there are only 10 tests between two different test files, here it is:
const fs = require('fs');
const assert = require('assert');
import * as jwt from 'jsonwebtoken';
import * as auth from '../services/authentication-service';
const JWT_ERROR_INVALID_SIG = 'invalid signature';
describe('MMD Integration', () => {
const SERVICE = "knox";
const SERVICE_ID = "aluna1";
const badPublicKeyFile = "badkey.pub";
describe('Service Config is accessible', () => {
it('should contain data', async (done) => {
let config: {} | null = null;
config = await auth.getServiceConfig().catch(err => {
console.log("caught getServiceConfig error:", err);
return null;
});
if (config != null) {
assert.include(Object.keys(config), SERVICE);
} else {
console.log("Test failed!");
}
});
});
describe('Public Key', () => {
describe('is valid', () => {
it('should decode successfully', async (done) => {
let config: {} | null = null;
config = await auth.getServiceConfig().catch(err => {
console.log("caught getServiceConfig error:", err);
return null;
});
let publicKey: string | null = null;
if (config) {
publicKey = await auth.getServicePublicKey(SERVICE, config).catch(err => {
console.log("caught getServicePublicKey error:", err);
return null;
});
const token = await auth.genJwt(SERVICE);
if (token == null) {
console.log("genJwt returned null: stopping test");
done();
} else if (!publicKey) {
console.log("No public key: stopping test");
done();
} else {
jwt.verify(token, publicKey, (err, decoded) => {
if (err) {
console.log("WARNING: valid public key failed!", err.message);
} else if (decoded && Object.keys(decoded).includes('vendor')) {
assert.include(Object.values(decoded), SERVICE);
} else {
console.log("Test failed!");
}
});
}
}
});
});
describe('is bad', () => {
const badPublicKey = fs.readFileSync(badPublicKeyFile);
it('should fail verify', async (done) => {
const token = await auth.genJwt(SERVICE);
if (token == null) {
console.log("genJwt returned null: stopping test");
done();
} else {
jwt.verify(token, badPublicKey, (err: any, decoded: any) => {
if (err) {
assert.equal(err.message, JWT_ERROR_INVALID_SIG);
} else {
console.log("WARNING: bad public key worked!", decoded);
}
});
}
});
});
});
describe('Verify Service', () => {
describe('with valid public key', () => {
it('should succeed', async (done) => {
try {
const token = await auth.genJwt(SERVICE);
if (token == null) {
console.log("genJwt returned null: stopping test");
done();
} else {
const result = await auth.verifyService(SERVICE, token).catch(err => {
console.log("caught verifyService error: stopping test", err);
throw new Error(err);
});
assert.equal(result, "OK");
}
} catch (err) {
assert.equal(err, "OK");
}
});
});
describe('with mismatch token', () => {
it('should fail', async (done) => {
try {
const result = await auth.verifyService(SERVICE, "xyz").catch(err => {
console.log("caught verifyService error: stopping test", err);
done();
});
} catch (err) {
assert.notEqual(err, "OK");
}
});
});
});
describe('Service as real MMD', () => {
it('should fail', async (done) => {
try {
const token = await auth.genJwt("mmd");
if (token == null) {
console.log("genJwt returned null: stopping test");
throw new Error('null token');
} else {
const result = await auth.verifyService("mmd", token).catch(err => {
console.log("caught verifyService error:", err);
throw new Error(err);
});
}
} catch (err) {
assert.notEqual(err, "OK");
console.log(err);
}
});
});
});
describe('Get Token from Request Header', () => {
const someToken = "fake-jwt";
const headers = {
'Content-Type': 'application/json'
, 'Authorization': 'Bearer ' + someToken
, 'Aluna-Service': 'foobar'
};
const badHeaders2 = {
'Content-Type': 'application/json'
, 'Authorization': someToken
, 'Aluna-Service': 'foobar'
};
describe('Request header has authorization', () => {
it('should return token', () => {
const result = auth.getTokenFromAuth(headers.Authorization);
assert.equal(result, someToken);
});
});
describe('Request header is missing authorization', () => {
it('should return null', () => {
const result = auth.getTokenFromAuth('');
assert.equal(result, null);
});
});
describe('Authorization is missing Bearer', () => {
it('should return null', () => {
const result = auth.getTokenFromAuth(badHeaders2.Authorization);
assert.equal(result, null);
});
});
});
import request from 'supertest';
import { app } from '../app';
it('renders a greeting to screen', () => {
return request(app).get('/').send({ greeting: 'howdy' }).expect(200);
})
This is what I see in the terminal:
Test Suites: 3 failed, 1 passed, 4 totaload:flatten Completed in 1ms
Tests: 9 failed, 11 passed, 20 total
Snapshots: 0 total
Time: 31.358 s
Ran all test suites.
Watch Usage
› Press f to run only failed tests.
› Press o to only run tests related to changed files.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
at Object.getCodec (node_modules/iconv-lite/lib/index.js:65:27)
at Object.getDecoder (node_modules/iconv-lite/lib/index.js:127:23)
at getDecoder (node_modules/raw-body/index.js:45:18)
at readStream (node_modules/raw-body/index.js:180:15)
at getRawBody (node_modules/raw-body/index.js:108:12)
[2022-03-07T18:40:25.852Z] 1.0.1-dev error: uncaughtException: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error: Caught error after test environment was torn down
This API was meant to work with Jest or that was the original testing suite installed, but someone else came behind and started using Mocha that they are using globally on their machine. Would anyone mind also sharing why tests would pass on their global install of Mocha but not on Jest?
Just wanted to post a solution which is not buried in comments.
By default jest will find any test files in your entire project. If you are building or copying files to a build/release directory, you need to do one of the following:
(Recommended) Exclude the test files from your build pipeline. I usually create a separate tsconfig for building which excludes the test files. Your build command should point to this tsconfig: tsc --project tsconfig.build.json. Note: you can extend tsconfigs so that you don't have to manage duplicates. Here's an example of what your tsconfig.build.json might look like:
{
"extends": "./tsconfig.json",
"exclude": ["src/**/*.test.ts"]
}
-- OR --
Exclude your build directories from jest, adding testPathIgnorePatterns: ['dist/'] to your jest.config.js (assuming your compiled JavaScript files are in the dist folder)

Restarting express server in esbuild

I am trying to create a simple express server with esbuild. These are my code
import express from "express";
const app = express();
const port = 3000;
const stopServer = {
stop: () => {},
};
export const createServer = async () => {
app.get("/", async (req, res) => {
res.json({
first: "Hello",
});
});
const server = app.listen(port, () => {
console.log(`Listening on port: ${port}`);
});
stopServer.stop = () => {
server.close();
};
};
export const stop = () => {
stopServer.stop();
stopServer.stop = () => {};
};
esbuild.config.js
const esbuild = require("esbuild");
const path = require("path");
const restartPlugin = () => {
return {
name: "restart-express",
setup(build) {
build.onEnd(async (res) => {
const { stop, createServer } = await import("../dist/server.js");
stop();
createServer();
});
},
};
};
const run = async () => {
await esbuild.build({
entryPoints: [path.resolve(__dirname, "../src/server.ts")],
outdir: path.resolve(__dirname, "../dist"),
platform: "node",
sourcemap: true,
format: "cjs",
watch: {
onRebuild: async (err, res) => {
if (err) {
console.error(err);
} else {
console.log("There is some change");
}
},
},
plugins: [restartPlugin()],
});
};
run();
Reference for plugin : https://github.com/evanw/esbuild/issues/1258#issuecomment-834676530
If you were to run this application It i will work initially but when you change the code, the server wont get updated even if you refresh the page.
I am not really sure where I am making mistake, Any help please
The problem is that node cache the import("..dist/server.js"), as a result it will never return new module. To solve this problem we will write a function
const purgeAppRequireCache = (buildPath) => {
for (let key in require.cache) {
if (key.startsWith(buildPath)) {
delete require.cache[key];
}
}
};
Which will remove the cache from the node. We can also use this function in this manner. Which solves my problem
const esbuild = require("esbuild");
const path = require("path");
const startPlugin = () => {
return {
name: "startPlugin",
setup(build) {
build.onEnd((res) => {
const serverPath = path.resolve(__dirname, "../dist/server.js");
const { stop } = require("../dist/server.js");
stop();
purgeAppRequireCache(serverPath);
purgeAppRequireCache(path.resolve(__dirname, "../src"));
const { listen } = require("../dist/server");
listen();
});
},
};
};
const run = async () => {
await esbuild.build({
entryPoints: [path.resolve(__dirname, "../src/server.tsx")],
outdir: path.resolve(__dirname, "../dist"),
platform: "node",
sourcemap: true,
format: "cjs",
watch: true,
bundle: true,
plugins: [startPlugin()],
});
};
run();
const purgeAppRequireCache = (buildPath) => {
for (let key in require.cache) {
if (key.startsWith(buildPath)) {
delete require.cache[key];
}
}
};
If you not reload runtime, the global's object and sub require(xxx) maby have same error.
You can use kill and fork cluster when change you code, it's same fast like require(xxx), there have example codes: https://github.com/ymzuiku/bike/blob/master/lib/index.js
If you need see kill and fork cluster example, here's a same feature package, also use esbuild, but it use fs.watch: https://www.npmjs.com/package/bike
Hope there could help you :)
#es-exec/esbuild-plugin-serve or #es-exec/esbuild-plugin-start are two alternative esbuild plugins that you can try. They run your bundles or any command line script for you after building your project (supports watch mode for rebuilding on file changes).
The documentation can be found at the following:
#es-exec/esbuild-plugin-serve
#es-exec/esbuild-plugin-start
Disclaimer: I am the author of these packages.

Cypress - check if the file is downloaded

I have a little problem with trying to check if a file is downloaded.
Button click generates a PDF file and starts its download.
I need to check if it works.
Can Cypress do this?
I would suggest you to have a look to the HTTP response body.
You can get the response with cy.server().route('GET', 'url').as('download') (check cypress documentation if you don't know these methods).
and catch the response to verify the body is not empty:
cy.wait('#download')
.then((xhr) => {
assert.isNotNull(xhr.response.body, 'Body not empty')
})
Or if you have a popup announcing success when the download went successfully, you can as well verify the existence of the popup:
cy.get('...').find('.my-pop-up-success').should('be.visible')
Best,
EDIT
Please note cy.server().route() may be deprecated:
cy.server() and cy.route() are deprecated in Cypress 6.0.0. In a future release, support for cy.server() and cy.route() will be removed. Consider using cy.intercept() instead.
According to the migration guide, this is the equivalent: cy.intercept('GET', 'url').as('download')
cypress/plugins/index.js
const path = require('path');
const fs = require('fs');
const downloadDirectory = path.join(__dirname, '..', 'downloads');
const findPDF = (PDFfilename) => {
const PDFFileName = `${downloadDirectory}/${PDFfilename}`;
const contents = fs.existsSync(PDFFileName);
return contents;
};
const hasPDF = (PDFfilename, ms) => {
const delay = 10;
return new Promise((resolve, reject) => {
if (ms < 0) {
return reject(
new Error(`Could not find PDF ${downloadDirectory}/${PDFfilename}`)
);
}
const found = findPDF(PDFfilename);
if (found) {
return resolve(true);
}
setTimeout(() => {
hasPDF(PDFfilename, ms - delay).then(resolve, reject);
}, delay);
});
};
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
on('before:browser:launch', (browser, options) => {
if (browser.family === 'chromium') {
options.preferences.default['download'] = {
default_directory: downloadDirectory,
};
return options;
}
if (browser.family === 'firefox') {
options.preferences['browser.download.dir'] = downloadDirectory;
options.preferences['browser.download.folderList'] = 2;
options.preferences['browser.helperApps.neverAsk.saveToDisk'] =
'text/csv';
return options;
}
});
on('task', {
isExistPDF(PDFfilename, ms = 4000) {
console.log(
`looking for PDF file in ${downloadDirectory}`,
PDFfilename,
ms
);
return hasPDF(PDFfilename, ms);
},
});
return config;
};
integration/pdfExport.spec.js
before('Clear downloads folder', () => {
cy.exec('rm cypress/downloads/*', { log: true, failOnNonZeroExit: false });
});
it('Should download my PDF file and verify its present', () => {
cy.get('ExportPdfButton').click();
cy.task('isExistPDF', 'MyPDF.pdf').should('equal', true);
});