Trouble connecting to SQL Server with Cypress - sql-server

Having an issue with where i seem to be connecting to SQL Server but cannot find the server/db.
I have been trying to follow the steps in this guide for Cypress 9 but to no avail.
https://www.npmjs.com/package/cypress-sql-server
There was an answer on SO that i've been trying to use but I can't reply to a comment and add a comment but it was deleted by the mods for some reason. This is the URL to the answer I have been trying to follow but can't connect.
How to configure cypress-sql-server with no cypress.json? (updated)
Has someone please got a working example?
cypress.config.ts
const { defineConfig } = require("cypress");
const sqlServer = require("cypress-sql-server");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// allows db data to be accessed in tests
config.db = {
"userName": "x",
"password": "x",
"server": "xxx\\SQLEXPRESS",
"options": {
"database": "xxxxxx",
"encrypt": true,
"rowCollectionOnRequestCompletion": true,
"trusted_connection": true
}
}
// code from /plugins/index.js
const tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
return config
// implement node event listeners here
},
},
});
export default defineConfig({
chromeWebSecurity: false,
videosFolder: 'cypress/videos',
screenshotsFolder: 'cypress/screenshots',
fixturesFolder: 'cypress/fixtures',
video: false,
reporter: 'cypress-mochawesome-reporter',
reporterOptions: {
reportDir: 'cypress/reports',
charts: true,
reportPageTitle: 'xxxxxxxx',
embeddedScreenshots: true,
inlineAssets: true,
},
e2e: {
// We've imported your old cypress plugins here.
// You may want to clean this up later by importing these.
setupNodeEvents(on, config) {
return require('./cypress/plugins/index.ts')(on, config)
},
experimentalSessionAndOrigin: true,
specPattern: 'cypress/e2e/tests/orders/*',
baseUrl: 'http://localhost:4200',
},
})
index.ts
const { defineConfig } = require('cypress')
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
require('cypress-mochawesome-reporter/plugin')(on);
return config;
}
e2e.ts
import '#cypress/code-coverage/support';
import './commands';
import 'cypress-mochawesome-reporter/register';
import sqlServer from 'cypress-sql-server';
sqlServer.loadDBCommands();
}
Tried creating a new sysadmin also on SQL Server in case it was an access issue

The TCP/IP Properties for your instance should look like this to make it listen on port 1433: On IPALL clear the TCP Dynamic Ports and set TCP Port to 1433.

You have the pattern for cypress.config.js plus the one for cypress.config.ts in your config file, but it's either/or not both at once.
See example Configuration.
Since you use typescript, try
import { defineConfig } from 'cypress'
import sqlServer from 'cypress-sql-server'
const dbSettings = {
"userName": "x",
"password": "x",
"server": "xxx\\SQLEXPRESS",
"options": {
"database": "xxxxxx",
"encrypt": true,
"rowCollectionOnRequestCompletion": true,
"trusted_connection": true
}
}
export default defineConfig({
chromeWebSecurity: false,
... // other cofinfig settings
e2e: {
setupNodeEvents(on, config) {
config.db = dbSettings;
const tasks = sqlServer.loadDBPlugin(dbSettings);
on('task', tasks);
return require('./cypress/plugins/index.ts')(on, config)
},
experimentalSessionAndOrigin: true,
specPattern: 'cypress/e2e/tests/orders/*',
baseUrl: 'http://localhost:4200',
},
})

Related

Nx advanced reverse proxy configuration

Migrating a react application to an Nx integrated workspace, and having an issue with advanced proxy configuration.
I understand that for a simple proxy...
Specify the proxy.conf.json file
"serve": {
"executor": "#nrwl/webpack:dev-server",
"defaultConfiguration": "development",
"options": {
"verbose": true,
"buildTarget": "ydsca:build",
"hmr": true,
**"proxyConfig": "apps/ydsca/proxy.conf.json",**
"ssl": true,
"sslKey": "certs/localhost.key.pem",
"sslCert": "certs/localhost.crt.pem"
},
Implement the proxy.conf.json file, e.g....
{
"/caconnect/common/*": {
"target": "https://127.0.0.1:9443",
"secure": false,
"logLevel": "debug"
}
}
This works without any issues, however, the current React application uses "http-proxy-middleware" and a more advanced setupProxy.js file (wildcard matching such as "/**/common/" for any patch that contains /common/):
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
[
'/**/common/',
'/**/commonClassic/',
'/**/ydscaCommon/',
'/ymca',
'/staff'
],
createProxyMiddleware({
//Must use 127.0.0.1 as for some reason, localhost stopped working in node versions > 16
target: 'https://127.0.0.1:9443',
//Necessary for https with self signed certificates
secure: false,
changeOrigin: false,
//Additional logging stuff!
onProxyReq: function onProxyReq(proxyReq, req, res) {
// Log outbound request to remote target
console.log('--> ', req.method, req.path, '->', proxyReq.baseUrl + proxyReq.path);
},
onError: function onError(err, req, res) {
console.error(err);
res.status(500);
res.json({error: 'Error when connecting to remote server.'});
},
//logLevel: 'debug'
})
);
};
How can the same advanced proxying be configured in Nx?
Tried changing proxyConfig": "apps/ydsca/proxy.conf.json" to proxyConfig": "apps/ydsca/setupProxy.js", but it doesn't seem to like javascript files for proxy configuration!
Any suggestions?
Thank you.

ASP.NET Web API/React SPA

I have followed exactly (multiple times) the .NET tutorial on creating a Weather Forecast API/SPA pair and the two are not able to communicate. Here is the error, which is reported in the console log of the React SPA:
Failed to load resource: the server responded with a status of 504
(Gateway Timeout) :3000/weatherforecast:1
I do not fully understand proxies but my understanding is that if the ports match, the process of sending data from the API to the SPA should work. Here are my current settings with respect to ports:
launchSettings.JSON (API)
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:8772",
"sslPort": 44311
}
},
"profiles": {
"API": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:7036;http://localhost:5036",
"dotnetRunMessages": true
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
setupProxy.js (React SPA)
const { createProxyMiddleware } = require('http-proxy-middleware');
const context = [
"/weatherforecast",
];
module.exports = function (app) {
const appProxy = createProxyMiddleware(context, {
target: 'https://localhost:8772',
secure: false
});
app.use(appProxy);
};
My understanding is that these two applications should be able to communicate because they have a common port of 8772, but I suppose my assumption must be wrong? Thanks for your support.

Next js jest coverage

I am using in my next js application Cypress and Jest. Running jest --coverage i get an error:
STACK: Error: Duplicate plugin / preset detected.
If you 'd like to use two separate instances of a plugin,
they need separate names, e.g.
plugins: [
['some-plugin', {}],
['some-plugin', {}, 'some unique name'],
]
This is my .babelrc file:
{
"presets": ["next/babel"],
"plugins": ["istanbul"]
}
Who faced with the same issue and how to solve it to get the coverage?
I found the solution that helped to solve the problem.
I had to add the env variable to the .babelrc
{
"env": {
"component": {
"plugins": [
"istanbul"
]
}
}
}
Then add it to cypress.config.js
const { defineConfig } = require('cypress');
const { devServer } = require('#cypress/webpack-dev-server');
const webpackConfig = require('./config/cypress.webpack.config.js');
const codeCoverageTask = require('#cypress/code-coverage/task');
module.exports = defineConfig({
viewportWidth: 1000,
viewportHeight: 660,
video: false,
env: {
BABEL_ENV: 'component',
},
component: {
devServer(devServerConfig) {
return devServer({
...devServerConfig,
framework: 'react',
webpackConfig,
});
},
specPattern: 'src/**/*.cy.{js,ts,jsx,tsx}',
setupNodeEvents(on, config) {
codeCoverageTask(on, config);
return config;
},
},
});

Attempted import error: 'Wallet' is not exported from '#project-serum/anchor'

Trying to import the Wallet class but getting error in title at runtime. This issue apparently should have been fixed in v0.21+ but it doesn't appear to work in my codebase.
Using nextjs v11.0.1 and #project-serum/anchor v0.23.0
Relevant snippet from index.tsx
import { Provider, Program, Wallet } from '#project-serum/anchor';
import { Keypair } from '#solana/web3.js';
const Page = () => {
const testWallet = new Wallet(Keypair.generate());
return <div></div>;
}
The above snippet DOES work when using #project-serum/anchor v0.16.2
next.config.js
const path = require('path');
const withTM = require('next-transpile-modules')([
'#blocto/sdk',
'#project-serum/sol-wallet-adapter',
'#solana/wallet-........,
]);
module.exports = withTM({
target: 'serverless',
distDir: 'build',
trailingSlash: true,
webpack5: false,
webpack(config) {
config.module.rules.push(
{
test: /\.svg$/,
issuer: {
test: /\.(js|ts)x?$/,
},
use: ['#svgr/webpack'],
},
{
test: /\.png$/,
issuer: {
test: /\.(js|ts)x?$/,
},
use: ['file-loader'],
},
{
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto',
},
);
config.resolve.alias = {
...config.resolve.alias,
assets: path.resolve(__dirname, './public/assets'),
};
config.node = {
fs: 'empty',
};
return config;
},
});
tsconfig.json
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"baseUrl": "./src",
"module": "esnext",
"paths": {
"assets/*": ["./public/assets/*"],
"#solana/*": ["./node_modules/#solana/*"]
},
"incremental": true
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
Hmm, not exactly sure if this is the same issue I had, but you can try to just re-create the Wallet type locally and imports it.
Looks like this for me
export class MyWallet implements Wallet {
constructor(readonly payer: Keypair) {
this.payer = payer
}
async signTransaction(tx: Transaction): Promise<Transaction> {
tx.partialSign(this.payer);
return tx;
}
async signAllTransactions(txs: Transaction[]): Promise<Transaction[]> {
return txs.map((t) => {
t.partialSign(this.payer);
return t;
});
}
get publicKey(): PublicKey {
return this.payer.publicKey;
}
}
I had to import Wallet like this in react
const { Wallet } = require("#project-serum/anchor");
Use NodeWallet instead of Wallet
import { Provider, Program, NodeWallet } from '#project-serum/anchor';
Using "#project-serum/anchor": "^0.14.0",
import * as anchor from '#project-serum/anchor';
anchor.web3.Keypair.generate().publicKey
anchor.web3.Keypair.generate().secretKey
Looks like, in that version that you are using, Wallet is not available and before, web3 was part of #project-serum/anchor. Then, they moved it into a separete package #solana/web3.js.
Solana dev tools reminds me of the beginning of solidity. Since it is a new and demanding technology, It changes rapidly

Jest throwing TypeError: Cannot read property 'fetch' of undefined

I'm trying to run some tests with Jest on my react/react-native library (only some business logic inside).
We are testing actions that uses fetch function (polyfill with whatwg-fetch).
I've added whatwg-fetch (thanks to Safari) for react.
Whenever i try to run a test, i'm getting this error:
TypeError: Cannot read property 'fetch' of undefined
at node_modules/whatwg-fetch/fetch.js:4:11
at Object.<anonymous> (node_modules/whatwg-fetch/fetch.js:461:3)
at Object.<anonymous> (node_modules/jest-expo/src/setup.js:138:416)
What can cause this issue? Is there a way in the jest config to avoid this?
Here are some files for debug:
Jest config in package.json
"jest": {
"preset": "jest-expo",
"moduleFileExtensions": [
"js",
"jsx",
"ts",
"tsx"
],
"verbose": true,
"transform": {
"^.+\\.(js|ts|tsx)$": "<rootDir>/node_modules/babel-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"testPathIgnorePatterns": [
"\\.snap$",
"<rootDir>/node_modules/",
"<rootDir>/dist/"
],
"transformIgnorePatterns": [
"node_modules/?!react-native"
]
},
Webpack config:
const config = {
entry: [
'whatwg-fetch',
__dirname + '/src/index.ts',
],
devtool: 'source-map',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.js',
library: 'checkinatwork-module',
libraryTarget: 'umd',
umdNamedDefine: true,
},
module: {
loaders: [
{ test: /\.(tsx|ts)?$/, loader: 'ts-loader', exclude: /node_modules/ },
],
},
resolve: {
modules: [
'./src',
'node_modules',
],
extensions: ['.js', '.ts', '.jsx', '.tsx', 'json'],
},
plugins: [
],
};
Test file:
import expect from 'expect';
import * as actions from '../../src/components/Checkin/checkin.action';
import * as reducers from '../../src/components/Checkin/checkin.reducer';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
describe('=> ADD CHECKIN ACTIONS', () => {
describe('- REQUEST', () => {
it('Action: ADD_CHECKIN_REQUEST should request addCawCheckin', () => {
const expectedAction = {
type: actions.ADD_CHECKIN_REQUEST,
isFetching: true,
};
expect(actions.addCheckinRequest())
.toEqual(expectedAction);
});
it('Reducer: newCheckin should trigger ADD_CHECKIN_REQUEST and initiate loading', () => {
const expectedState = {
isFetching: true,
status: null,
};
expect(reducers.newCheckin(reducers.newCheckinDefaultState, actions.addCheckinRequest()))
.toEqual(expectedState);
});
});
Action file:
export const getCheckins = (sessionId, date, url, isRefresh) => {
const config = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sessionId: {sessionId},
date: {date},
}),
};
return dispatch => {
if (!isRefresh) {
dispatch(getCheckinsRequest());
}
return fetch(url + 'getCAWCheckIns', config)
.then(response => response.json())
.then(({ checkins }) => {
dispatch(getCheckinsSuccess(checkins));
}).catch(err => {
dispatch(getCheckinsError('Get checkins failed'));
console.error('Get checkins failed: ', err);
});
};
};
Thanks!
I've done it in the spec with:
import { fetch } from 'whatwg-fetch';
global.fetch = fetch;
And it has worked as expected with Jest.
might be late to the game, but this worked for me.
Possible solution #1
Note: React.PropTypes is deprecated as of React v15.5. Please use the prop-types library instead.
If you install the npm package prop-types, it has isomorphic-fetch as a dependency. This will give you fetch as a global. You will still need to import it into your test file. You might need to exclude it from your linter too.
add this to the top of the test file.
import fetch from 'isomorphic-fetch'
I didn't need to call fetch in the test suite, but I needed to make it available.
If you use this approach, I think you would remove the 'whatwg-fetch', from your webpack entry
Hope this helps
Updated: Possible solution #2
Using the example of #zvona from above, but create a MOCKS folder in your app. then a file /globalMock.js. You might not have set it up properly.
__MOCKS__/globalMock.js
// use one of these imports
import { fetch } from 'whatwg-fetch' // if you want to keep using the polyfill
import { fetch } from 'isomorphic-fetch' // from a dependency node module that I spoke of in the previous solution.
global.fetch = fetch
Now in package.json
add this to your Jest configuration:
"jest": {
"verbose": true,
"rootDir": "app",
"setupFiles": ["<rootDir>/__MOCKS__/globalMock.js"]
}
this will allow the use of fetch in your tests.
I also had to use this same concept for localStorage. Where I keep all of my globals that Jest doesn't have access.
Upgrading react-native, jest, and babel-jest to the latest versions fixed this issue for us.
This worked for me. In your expo set up file(node_modules/jest-expo/src/setup.js) where it requires whatwg-fetch, I changed that require to require('fetch-everywhere')
const { Response, Request, Headers, fetch } =
require('fetch-everywhere');
global.Response = Response;
global.Request = Request;
global.Headers = Headers;
global.fetch = fetch;
For some reasons, only fetch everywhere was working with expo and jest.

Resources