I haven't been able to figure out how to setup my cypressJs environments correctly to test. I'd love some help.
In my index.html file, in the <script> area, i am adding a CONFIG object. In production, this config object is added in by the MVC app. This config object can have many different states (some info might be missing or different for each user). In the cypress.json file, under "env" I have this same object. I use this in the spec.js files by calling Cypress.env("CONFIG"); which works just fine.
However, I want to change the state of the app/environment variable for different tests. Is this possible?
I'd like to run a spec file using a CONFIG that has all the data and one spec file using a CONFIG object that is missing data (ex. address == null) so I can test properly under both circumstances.
Is this possible or am I doing something fundamentally wrong?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script>
CONFIG = {
dealer: {
id: 19285,
address: "343 Somewhere Lane SpringField, TN 47383",
name: "HUDSON TRACTOR & RENTAL EQUIPMENT & OTHER HEAVY THINGS
}
</script>
</head>
</html>
cypress.json
{
"env": {
"CONFIG": {
dealer: {
id: 19285,
address: "343 Somewhere Lane SpringField, TN 47383",
name: "HUDSON TRACTOR & RENTAL EQUIPMENT & OTHER HEAVY THINGS
}
}
}
}
It is more of a best practice to run spec files against a single environment one at a time. It is either you use an overriding cypress.env.json or create 2 config files for each environment (test and prod for example) which will override env variables both set in cypress.env.json and cypress.json. https://docs.cypress.io/guides/guides/environment-variables.html#Option-2-cypress-env-json
However, if you want a quick and dirty solution to your issue above (I don't suggest this), you can set your spec files with the below:
cypress.json
{
"env": {
"CONFIG": {
"id": "19285",
"address": "343..."
},
"CONFIG_PROD": {
"id": "19285",
"address": ""
}
}
}
spec_1.js
const config = Cypess.env("CONFIG")
spec_2.js
const config = Cypress.env("CONFIG_PROD")
or just simply put them under fixture files (which I believe is more appropriate for this case):
config.json
{
"test": {
"id": "19285",
"address": "343..."
},
"prod": {
"id": "19285",
"address": ""
}
}
spec_1.js
import {test, prod} from '../fixtures/config.json'
const address = test.address
const address_null = prod.address //If you would like to run this on another 'it' test
spec_1.js
import {prod} from '../fixtures/config.json'
const address_null = prod.address
Related
I'm trying to set a base url for both my dev and prod environments, but vitejs configs are not resolved.
According to vitejs , you can set the base public path when served in development or production, in your config options.
When running vite from the command line, Vite will automatically try to resolve a config file named vite.config.js inside project root.
The issue is that my application requests don't go through 'http://localhost:8080/', but are still appended to the default serving port http://localhost:3000/.
My current configs are bellow:
// vite.config.js
export default {
base: 'http://localhost:8080/'
}
// packages.json
{
"name": "vue3ui",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
...,
"vue": "^3.0.11"
},
"devDependencies": {
"#vue/compiler-sfc": "^3.0.11",
"vite": "^1.0.0-rc.13"
}
}
Not totally clear to me but I will try to give you an answer to achieve what you want.
I'm trying to set a base url for both my dev and prod environments
Edit: I read again you question, and I think you are looking for the point C on this answer.
Changes should be made in vite.config.js
A) You are looking to change the running port from 3000 to 8080, adjust server.port
server: {
port: '8080'
}
B) But if you are looking to run on localhost:3000 and forward requests to localhost:8080 then you have to adjust server.proxy
server: {
proxy: {
'/': {
target: 'http://localhost:8080/'
},
'/admin': {
target: 'http://localhost:8081/'
}
}
}
example:
'/': will proxy all requests to localhost:8080
'/admin': will proxy only requests that have as endpoint /admin to http://localhost:8081
C) Changing base path depending on dev or prod environment
.env file :
// .env
// Running locally
APP_ENV=local
// you change port of local/dev here to :8000
// do not forget to adjust `server.port`
ASSET_URL=http://localhost:3000
// Running production build
APP_ENV=production
ASSET_URL=https://your-prod-asset-domain.com
vite.config.js:
const ASSET_URL = process.env.ASSET_URL || '';
export default {
base: `${ASSET_URL}/dist/`,
[...]
}
If it's not what you are looking for, please be more precise and I will edit my answer.
For more information, head to the official doc at https://vitejs.dev/config/#server-options
I think I understand what TC wants to solve.
He has 1 build for dev and prod envs.
But it depends on envs, he has a different base path.
Answer:
https://vitejs.dev/guide/build.html#advanced-base-options
At the moment it is an experimental feature
experimental: {
renderBuiltUrl(filename: string, { hostType }: { hostType: 'js' | 'css' | 'html' }) {
if (['js', 'css'].includes(hostType)) {
return { runtime: `window.__getFile(${JSON.stringify(filename)})` }
} else {
return { relative: true }
}
}
}
and create global function
window.__getFile = function(file){
if (window.location.host.includes('dev')) {
return `http://cdn.dev/${file}`
}
return `http://cdn.prod/${file}`
}
P.s. Sorry. I can't find any example with port
I was able to deploy a Create-React-App and express back-end with now.sh
but the problem is that it only gets the home route(I can route to /about from home but on page reload/refresh, i get a 404 error). I have tried several config. Please i need help.
"public": false,
"version": 2,
"builds": [
{
"src": "server/index.js",
"use": "#now/node",
"config": {
"maxLambdaSize": "20mb"
}
},
{
"src": "package.json",
"use": "#now/static-build",
"config": {
"distDir": "build"
}
}
],
"routes": [
{
"src": "/api/(.*)",
"dest": "/server/index.js"
},
{
"src": "/(.*)",
"dest": "/build/$1"
}
]
}
This sounds like a problem described here - https://create-react-app.dev/docs/deployment/
If you use routers that use the HTML5 pushState history API under the hood (for example, React Router with browserHistory), many static file servers will fail. For example, if you used React Router with a route for /todos/42, the development server will respond to localhost:3000/todos/42 properly, but an Express serving a production build as above will not.
This is because when there is a fresh page load for a /todos/42, the server looks for the file build/todos/42 and does not find it. The server needs to be configured to respond to a request to /todos/42 by serving index.html. For example, we can amend our Express example above to serve index.html for any unknown paths:
app.use(express.static(path.join(__dirname, 'build')));
-app.get('/', function (req, res) {
+app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
When users install your app to the homescreen of their device the default configuration will make a shortcut to /index.html. This may not work for client-side routers which expect the app to be served from /. Edit the web app manifest at public/manifest.json and change start_url to match the required URL scheme, for example:
"start_url": ".",
This helped when I had 404 with Zeit - https://itnext.io/fix-404-error-on-single-page-app-with-zeit-now-b35b8c9eb8fb -
In order to solve the 404 error message, we have to make sure that when a user goes to any URL which is not the root URL (e.g. www.myapp.com/something or www.myapp.com/dashboard/example) and they have never loaded our web app before, they are redirected to the root URL. Once they have loaded the root URL then they can be redirected back to the page they were trying to access and everyone is happy!
Step 1 - in your project's public folder make another package.json file -
{
"name": "myapp-spa",
"version": "1.0.0",
"scripts": {
"start": "serve --single --cache=60000"
},
"dependencies": {
"serve": "latest"
}
}
Step 2 - Configure the 404 page
Now that our files are being served, if a person goes to a non-root URL, the server will look for a 404.html file to send them instead. This is our chance to redirect them and take them to the index.html page. Put the 404.html file in the same public folder as the index file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>404 Not Found | My App</title>
</head>
<body>
<script>
(function redirect() {
if (document && document.location) {
document.location.replace(`/?redirect=${encodeURIComponent(document.location.pathname)}`);
}
}());
</script>
</body>
</html>
Step 3. - Prepare for deployments
Now that, we have our redirect code, all we have to do is add a deploy command to our original myapp/package.json (this is not the file we created earlier):
{
"scripts": {
...
"deploy": "yarn run build && now ./build --name=myapp-spa",
"start": "react-scripts start",
"build": "react-scripts build",
...
}
}
Sweet, now all we need to do is call yarn run deploy and our app should stop getting the 404 error pages.
Step 4: Clean up
In order to get back to the page we originally requested e.g. myapp.com/something we need to redirect the page to the ?redirect parameter we set earlier in the tutorial. To do this, we need to install the query-string library to parse the parameter. Then you can include the following code into your app in a place that loads after your routing code loads.
const queryString = require('query-string');
...
const params = queryString.parse(document.location.search);
const redirect = params.redirect; // this would be "abcdefg" if the query was "?redirect=abcdefg"
if (document.location.pathname === '/' && redirect) {
document.location.assign(`${document.location.origin}/${redirect}`);
}
It’s important that you do not redirect the user with the above code until after the routing code is cached in the browser. Once you’ve finished, your app should be working just as it should be.
Basically pasted the whole thing, but make sure to check the article.
Apparently there's another possible solution, might be worth trying:
{
...
"builds": [
{ "src": "build/**", "use": "#now/static" }
],
"routes": [
{
"src": "/(.*)\\.(.*)",
"dest": "/build/$1.$2"
},
{
"src": "/",
"dest": "/build/index.html"
},
{
"src": "/(.*)",
"status": 301, "headers": { "Location": "/" }
}
]
I followed this doc to add CSS reset to my app.
https://create-react-app.dev/docs/adding-css-reset/#indexcss
But it showed this message:
"stylelint": {
"extends": "stylelint-config-recommended",
"rules": {
"at-rule-no-unknown": null
}
How to fix this problem?it is annoying...
To fix this warning you just need to add this line to.vscode/settings.json inside your project (you can create this file if it doesn't already exist):
{
"css.lint.unknownAtRules": "ignore"
}
Source: https://create-react-app.dev/docs/adding-css-reset/#indexcss
For VS Code -
To make the VS Code recognise this custom CSS directive, you can provide custom data for VS Code's CSS Language Service as mentioned here - https://github.com/Microsoft/vscode-css-languageservice/blob/master/docs/customData.md.
Create a CSS custom data set file with the following info. Place it at location .vscode/custom.css-data.json relative to the project root.
{
"version": 1.1,
"properties": [],
"atDirectives": [
{
"name": "#import-normalize",
"description": "bring in normalize.css styles"
}
],
"pseudoClasses": [],
"pseudoElements": []
}
Now, if you don't have already, create a .vscode\settings.json file relative to project root. Add a field with key "css.customData" and value as the path to custom data set. For example,
{
"css.customData": ["./.vscode/custom.css-data.json"]
}
Now, you will no longer get "Unknown at rule" warning. When you hover over "#import-normalize", you will see the description you set for it in custom.css-data.json
#import-normalize is a non-standard at-rule. From the rule's documentation:
This rule considers at-rules defined in the CSS Specifications, up to and including Editor's Drafts, to be known.
However, the rule has an ignoreAtRules secondary option for exactly this use case, where you can list the non-standard imports you are using.
For example, in your package.json:
{
"stylelint": {
"extends": "stylelint-config-recommended",
"rules": {
"at-rule-no-unknown": [true, {
"ignoreAtRules": ["import-normalise"]
}]
}
}
}
Or within your .stylelintrc file:
{
"extends": "stylelint-config-recommended",
"rules": {
"at-rule-no-unknown": [true, {
"ignoreAtRules": ["import-normalise"]
}
}
}
I'm creating a custom linting rule in lesshint.
I want to access the filename of the file being walked.
Current code:
module.exports = {
name: 'customrule',
nodeTypes: ['decl'],
lint: function(config, node) {
console.log(node.root().source.input.from);
}
};
The closest I've got is node.root().source.input.from which seems to output the index of the file, but not its name.
config object seems to be a boolean
Lead maintainer of lesshint here.
I've just pushed an update where the full file path will be included on all nodes. You can access it via the source property, like this:
module.exports = {
name: 'customrule',
nodeTypes: ['decl'],
lint: function(config, node) {
console.log(node.source.input.file)
}
};
The value of config will be the value you specified for it in your .lesshintrc file. For example:
{
"customrule": {
"enabled": true,
"option": false
}
}
Will pass that object in config.
Link to the newly released version: https://github.com/lesshint/lesshint/releases/tag/v4.6.2
I'm trying to upgrade an existing express site to use kraken.js
I've got my dynamic pages loading ok (so far), but I can't seem to serve static files.
Looking at the example, pages, it seems simple enough that I just have to add
"middleware": {
"static": {
"arguments": [ "path: ./client" ]
}
}
In my config.json file. The file I'm trying to serve is ./client/build/js/bundle.js, and I can confirm that the file exists in the folder. It is NOT in a ./public folder.
What do I need to do to get kraken (or kraken.js static-serve) to find my static files?
I've placed the file in a ./public/client/build/js/bundle.js and kraken has no problem finding the file in that location.
I think you might be missing the "module" member of the middleware object. My current Kraken-generated static middleware config object looks like this:
"static": {
"module": {
"arguments": [ "path:./.build" ]
}
}
OK, I found out how to make it work. Notice how in your config that "public" isn't in there? That meant it was being pre-pended or configured somewhere else. That somewhere else is in /node-modules/kraken-js/config/config.json. I amended it to look like this:
"static": {
"enabled": true,
"priority": 40,
"module": {
"name": "serve-static",
"arguments": [ "path:./public", "path:./client" ]
}
},
Then in your regular /config/config.json I edited the static object to look like this:
"static": {
"module": {
"arguments": [ "path:./.build", "path:./build" ]
}
},
Notice that in the second argument there is not a "." before build.
Finally, I used script tags that looked like this in the master layout:
<script src="/js/test.js"></script>
So, from your root project directory I have /client/build/js/test.js and test.js loads correctly.
Also, there is one more way to do it that is easier and doesn't require mucking about in the kraken source. In your main index.js file you can do this:
app = module.exports = express();
app.use(kraken(options));
app.use(express.static('client')); // Add this line
Days, then weeks, then months went by, and nothing worked.
I should have noted that I am not using Yoeman, and we use gulp at work, which may have been part of the problem.
The solution turned out to be
"middleware": {
"static": {
"route": "/public"
},
which looks very different to any of the documentation from kraken. Hope this helps somebody.