Synpress cannot use cy.acceptMetamaskAccess (is not a function) - javascript

I'm trying to use Synpress, but I fail to understand how to solve
TypeError: cy.acceptMetamaskAccess is not a function
Let me share the relevant code* (I mostly followed this tutorial https://medium.com/andamp/how-to-setup-synpress-for-wen3-dapp-frontend-test-automation-with-metamask-73396896684a)
*if something is missing, please let me know
package.json:
{
"devDependencies": {
"#testing-library/cypress": "^8.0.2",
"cypress": "^9.7.0"
},
"scripts": {
"cypress:open": "cypress open",
"test": "env-cmd -f .env npx synpress run -cf synpress.json --config supportFile='tests/support/index.js'",
"test:watch": "env-cmd -f .env npx synpress open -cf synpress.json"
},
"dependencies": {
"#synthetixio/synpress": "^1.2.0",
"env-cmd": "^10.1.0"
}
}
How I configured my synpress.json
{
"baseUrl": "https://dappify.com/",
"userAgent": "synpress",
"retries": { "runMode": 0, "openMode": 0 },
"integrationFolder": "tests/integration",
"screenshotsFolder": "screenshots",
"videosFolder": "videos",
"video": true,
"chromeWebSecurity": true,
"viewportWidth": 1366,
"viewportHeight": 850,
"component": {
"componentFolder": ".",
"testFiles": "**/*spec.{js,jsx,ts,tsx}"
},
"env": {
"coverage": false
},
"defaultCommandTimeout": 30000,
"pageLoadTimeout": 30000,
"requestTimeout": 30000,
"supportFile": "tests/support/index.js"
}
Simple test
describe('Test User Login', () => {
it('Connects with Metamask', () => {
cy.visit('https://dappify.com')
cy.contains('Sign').click();
cy.contains('Confirm').click();
cy.contains('Connect Wallet').click();
cy.contains('Metamask').click();
cy.switchToMetamaskWindow();
cy.acceptMetamaskAccess().should("be.true");
})
})
I don't understand why cy.acceptMetamaskAccess() is not a function, I can find it here: https://github.com/synthetixio/synpress/blob/master/support/index.d.ts
How can I use the functions listed in this index.d.ts file?
** Solution **
Answer by Fody was helpful! Let me summarise the steps needed:
inside support folder you need an index.js
inside index.js
import './commands'
import "#synthetixio/synpress/support";
If you want to add custom functions add this file to support too
inside commands.js:
import "#testing-library/cypress/add-commands";
// here go(es) your custom function(s)

It's a bit hard to untangle the Synpress structure. Usually with a plugin library you import a support component and that adds the library's custom commands to your test.
The article says
Run your tests with env-cmd -f .env npx synpress run -cf synpress.json --config supportFile='support/index.js'
which makes me think the last parameter is bringing in the custom commands.
If you already tried that, the following is the command definition, you can try adding it at the top of your spec.
Cypress.Commands.add('acceptMetamaskAccess', allAccounts => {
return cy.task('acceptMetamaskAccess', allAccounts);
})

Related

jest js in vue/nuxt3 does not work, jest unexpected token issue

I want to test a component for my vue nuxt3 project and i got error when i test with js. The problem is,
> test
> jest
FAIL __tests__/test.js
● 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:
C:\Users\Emirhan\Desktop\Emir\amazon-backend\__tests__\test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { mount } from '#vue/test-utils';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-cli/node_modules/jest-runtime/build/index.js:1598:14)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.104 s
Ran all test suites.
when i , npm run test. it does not work.
Here is jest.config.js
module.exports = {
preset: '#vue/cli-plugin-unit-jest',
testEnvironment: 'jsdom'
}
Here my test.js,
import {mount} from '#vue/test-utils';
import MainSignUp from '#/components/MainSignUp.vue';
describe('SignUp component unit test: ', () => {
test('renders task 111', () => {
const wrapper = mount(MainSignUp, {
propsData: {
user: {name:"user 123",
completed:false
}
}
});
expect(wrapper.isVueInstance()).toBeTruthy();
});
test('renders task 222', () => {
const wrapper = mount(MainSignUp, {
propsData: {
user: {name:"user 321321312",
completed:false
}
}
});
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
And here is my package.json file,
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"test": "jest",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"#vue/vue3-jest": "28",
"jest": "^29.4.1",
"jest-environment-jsdom": "^29.4.1",
"nuxt": "^3.1.0",
"vue3-jest": "^27.0.0-alpha.1"
},
"dependencies": {
"#nozomuikuta/h3-cors": "^0.2.0",
"#nuxtjs/vuetify": "^1.12.3",
"#pinia/nuxt": "^0.4.6",
"#vue/cli-plugin-unit-jest": "^5.0.8",
"#vue/test-utils": "^2.2.8",
"axios": "^1.2.6",
"body-parser": "^1.20.1",
"express": "^4.18.2",
"firebase": "^9.16.0",
"nuxt-vuefire": "^0.1.5",
"pinia": "^2.0.29",
"sass": "^1.57.1",
"vuefire": "^3.0.1",
"vuetify": "^3.1.2"
},
"overrides": {
"vue": "latest"
}
}
I can not solve this issue. What can i do ?

Electron-Prisma Error: can not find module '.prisma/client'

I'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :
A javascript error occurred in the main process
Uncaught exception:
Error: can not find module : '.prisma/client'
I tried changing prisma provider output to ../resources/prisma/client
generator client {
provider = "prisma-client-js"
output = "../resources/prisma/client"
}
and in main.js of electron
const { PrismaClient } = require('../resources/prisma/client');
const prisma = new PrismaClient()
but I get error Cannot find module '_http_common' at webpackMissingModules in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on background.js (main.js of the my boilerplate)
I'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:
appId: com.example.app
productName: nuxt-electron-prisma
copyright: Copyright © 2021
nsis:
oneClick: false
perMachine: true
allowToChangeInstallationDirectory: true
directories:
output: dist
buildResources: resources
files:
- "resources/prisma/database.db"
- "node_modules/.prisma/**"
- "node_modules/#prisma/client/**"
- from: .
filter:
- package.json
- app
publish: null
and still get errors
in my win-unpacked/resources I have this only: win-unpacked\resources\app.asar.unpacked\node_modules\#prisma\engines
and of course my package.json
{
"private": true,
"name": "nuxt-electron-prisma",
"productName": "nuxt-electron-prisma",
"description": "",
"version": "1.0.0",
"author": "",
"main": "app/background.js",
"scripts": {
"dev": "nuxtron",
"build": "nuxtron build"
},
"dependencies": {
"electron-serve": "^1.0.0",
"electron-store": "^6.0.1",
"#prisma/client": "^3.0.2"
},
"devDependencies": {
"#mdi/font": "^6.1.95",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.12.1",
"core-js": "^3.15.1",
"electron": "^10.1.5",
"electron-builder": "^22.9.1",
"glob": "^7.1.7",
"noty": "^3.2.0-beta",
"nuxt": "^2.15.7",
"nuxtron": "^0.3.1",
"sass": "1.32.13",
"swiper": "^5.4.5",
"prisma": "^3.0.2",
"vue-awesome-swiper": "^4.1.1"
}
}
The solution provided by Mojtaba Barari works but it results in #prisma packages being present in both resources/app/node_modules and resources/node_modules.
There is a better way how to do it:
{
"build": {
"extraResources": [
{
"from": "node_modules/.prisma/client/",
"to": "app/node_modules/.prisma/client/"
}
],
}
}
In this case, the Prisma client files will be copied directly to resources/app/node_modules where other #prisma packages are already present and so you will save ~ 10 MB compared to the other solution.
EDIT:
My previous solution doesn't work if an application is packaged into an asar archive. You need to use files field instead:
{
"build": {
"files": [
{
"from": "node_modules/.prisma/client/",
"to": "node_modules/.prisma/client/"
}
],
}
}
This is a universal solution which works even if you don't use an asar archive.
Ok, I finally solved it!!
first of all no need to change client generator output direction!
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:../resources/database.db"
}
generator client {
provider = "prisma-client-js"
// output = "../resources/prisma/client" !! no need for this!
}
then in electron-builder config add ./prisma , #prisma and database
// my config file was a .yml
extraResources:
- "resources/database.db"
- "node_modules/.prisma/**/*"
- "node_modules/#prisma/client/**/*"
// or in js
extraResources:[
"resources/database.db"
"node_modules/.prisma/**/*"
"node_modules/#prisma/client/**/*"
]
this solved `Error: cannot find module : '.prisma/client'
but this alone won't read DB in built exe file!
so in main.js where importing #prisma/client should change DB reading directory:
import { join } from 'path';
const isProd = process.env.NODE_ENV === 'production';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
datasources: {
db: {
url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,
},
},
})
with these configs I could fetch data from my sqlite DB

Getting ParseError: Identifier is expected on importing svelte files for testing with jest

My Jest config details are
jest.config.js
module.exports = {
transform: {
'^.+\\.svelte$': 'svelte-jester',
'^.+\\.js$': 'babel-jest',
},
moduleFileExtensions: ['js', 'svelte'],
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}
package.json
.
.
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"babel-jest": "^26.0.1",
"jest": "^26.0.1",
"svelte-jester": "^1.0.6",
"#testing-library/svelte": "^3.0.0"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack",
"dev": "webpack-dev-server --content-base public",
"test": "jest src",
"test:watch": "npm run test -- --watch"
},
.
.
I created src/test folder where my test.spec.js is as follows
import {fireEvent, render} from '#testing-library/svelte';
import App from '../App.svelte';
describe('test', () => {
test('Just a mock test', async () => {
const myMock = jest.fn();
console.log(myMock());
myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock());
});
});
Plz note that this I used a jest mock function just for testing purpose but whenever I import a svelte file as in this case App.svelte I get an error as below
FAIL src/test/test.spec.js
● Test suite failed to run
ParseError: Identifier is expected
I found a possible solution to this parsing error. Apparently, the IDE was unable to resolve certain style classes in the test.svelte file defined inside style tag, which is why it was showing up ParseError.
I would suggest anyone coming across this error to check your svelte file thoroughly for errors since svelte-testing-lib parses through the entire file before executing any test function.

How to configure jest with babel

I'm configuring simple project for testing using jest and babel. How do i make them work together ?
I have tried instructions mentioned here: https://jestjs.io/docs/en/getting-started but couldn't accomplish it.
abc.test.js
import {PI} from "./mathconsts";
describe("tests",()=>{
test('assert pi', () => {
expect(PI).toBe(3.14);
});
});
mathconsts.js
export const PI = 3.14;
package.json
{
"name": "simple-testing",
"version": "1.0.0",
"description": "Project to write simple tests",
"main": "index.js",
"scripts": {
"test": "jest"
},
"dependencies": {
"axios": "0.19.0",
"dotenv": "8.1.0"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"babel-jest": "^24.9.0",
"jest": "24.9.0",
"prettier": "1.18.2"
}
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
jest.config.js
module.exports = {
transformIgnorePatterns: [
"/node_modules/"
],
}
error found:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
/Users/tests/abc.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { PI } from "./mathconsts";
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
How do i make it run ?

Test coverage in Mocha with Blanket doesn't work

I have a Node app I'd like to test, and get coverage report. I followed the Getting Started Guide but it doesn't seem to work.
My source, in src/two.js:
var two = 1 + 1;
module.exports = two;
My test, in test/two.js:
var expect = require('expect');
var two = require('../src/two');
describe('two', function() {
it('should be 2', function(done) {
expect(two).toBe(2);
done();
});
});
And my package.json:
{
"scripts": {
"test": "mocha",
"cover": "mocha -r blanket -R html-cov > coverage.html"
},
"devDependencies": {
"blanket": "^1.2.1",
"expect": "^1.13.4",
"mocha": "^2.3.4"
}
}
When I run npm run test everything works as you'd expect. But when I run npm run cover, in my coverage.html file I get 0% coverage 0 SLOC and nothing else.
I got it to run by adding this to package.json:
...
"config": {
"blanket": {
"pattern": "src",
"data-cover-never": ["node_modules"]
}
},
...
Apparently Blanket does not default to src despite what the guide says (there's an old open issue on GitHub).
It also tries to cover all of the paths that match the pattern, not just the src dir, so in this case it tried to cover external files as well (node_modules/has/src/index.js, which was installed by Expect). I had to add the data-cover-never to avoid it.

Categories