I am new to testcafe. I do not want to use maximizeWindow() over and over inside every test. Is there a way to have this feature to be used as part of the configuration file? Or a better solution that will prevent me using it inside every test.
You can use global hooks from the 1.19.0 TestCafe version. Add them to the config file. For example:
module.exports = {
hooks: {
test: {
before: async (t) => {
await t.maximizeWindow();
},
},
},
};
You can find more information on this feature in the documentation: https://testcafe.io/documentation/402638/reference/configuration-file#hooks
Related
I have an esbuild config taken straight from the docs:
import * as esbuild from 'esbuild'
let ctx = await esbuild.context({
entryPoints: ['./js/app.js'],
outdir: 'static',
bundle: true,
minify: true,
sourcemap: true,
plugins: [
postcss,
],
})
await ctx.watch()
let { host, port } = await ctx.serve({
servedir: 'static',
})
But I need to add some plugins, which are all still in commonjs (the esbuild-postcss plugin is a good example).
When I try to add require('esbuild-postcss') I get the error:
ReferenceError: require is not defined in ES module scope, you can use import instead
Which makes sense - but does this mean I can't use any esbuild plugins until they are converted to es modules?
Note: I know I can go back to a commonjs esbuild config, but as far as I can tell I won't be able to use the serve option if I do that.
Looking for some help to understand what is going on here.
The Problem
We are using a translation service that requires creating JSON resource files of copy, and within these resource files, we need to add some specific keys that the service understands so it knows what should and should not be translated.
To do this as simple as possible I want to import JSON files into my code without them being tree shaken and minified. I just need the plain JSON file included in my bundle as a JSON object.
The Solution - or so I thought
The developers at the translation service have instructed me to create a webpack rule with a type of assets/source to prevent tree shaking and modification.
This almost works but the strange thing is that the JSON gets added to the bundle as a string like so
module.exports = "{\n \"sl_translate\": \"sl_all\",\n \"title\": \"Page Title\",\n \"subtitle\": \"Page Subtitle\"\n}\n";
This of course means that when I try and reference the JSON values in my JSX it fails.
Test Repo
https://github.com/lukehillonline/nextjs-json-demo
NextJs 12
Webpack 5
SSR
Steps To Reproduce
Download the test repo and install packages
Run yarn build and wait for it to complete
Open /.next/server/pages/index.js to see the SSR page
On line 62 you'll find the JSON object as a string
Open .next/static/chunks/pages/index-{HASH}.js to see the Client Side page
If you format the code you'll find the JSON object as a string on line 39
Help!
If anyone can help me understand what is going wrong or how I can improve the webpack rule to return a JSON object rather than a string that would be a massive help.
Cheers!
The Code
next.config.js
module.exports = {
trailingSlash: true,
productionBrowserSourceMaps: true,
webpack: function (config) {
config.module.rules.push({
test: /\.content.json$/,
type: "asset/source",
});
return config;
},
};
Title.content.json
{
"sl_translate": "sl_all",
"title": "Page Title",
"subtitle": "Page Subtitle"
}
Title.jsx
import content from "./Title.content.json";
export function Title() {
return <h1>{content.title}</h1>;
}
pages/index.js
import { Title } from "../components/Title/Title";
function Home({ dummytext }) {
return (
<div>
<Title />
<p>{dummytext}</p>
</div>
);
}
export const getServerSideProps = async () => {
const dummytext = "So we can activate SSR";
return {
props: {
dummytext,
},
};
};
export default Home;
As a part of Automation testing, I want to point my Testcafe tests to a Test Prod server (Green) with the help of Custom Headers.
How can I pass custom headers to chrome instance while launching to perform tests as arguments.
Tried chrome:userProfile but the headers change for every release.
Require a generic way to pass custom headers.
Note: Testcafe script changes are not preferable.
Google Chrome doesn't allow setting request headers from the command line, but you can use the request hook to add a header value based on the environmental variable.
Please refer to the following example. Note that RequestLogger was added only for demonstration purposes:
// test.js
import { RequestLogger, RequestHook } from 'testcafe';
fixture `Set a Custom Referer`
.page`http://example.com/`;
export class MyRequestHook extends RequestHook {
constructor(requestFilterRules, responseEventConfigureOpts) {
super(requestFilterRules, responseEventConfigureOpts);
}
async onRequest(event) {
event.requestOptions.headers['CustomHeader'] = process.env.HEADER_VALUE;
}
async onResponse(event) {
}
}
const hook = new MyRequestHook();
const logger = RequestLogger(
["https://devexpress.github.io/testcafe/example/", "http://example.com/"],
{
logRequestHeaders: true,
}
);
test
.requestHooks([hook, logger])
('Check the Referer Value', async t => {
await t
.navigateTo('https://devexpress.github.io/testcafe/example/')
.expect(logger.contains(r => r.request.url === 'https://devexpress.github.io/testcafe/example/')).ok()
.expect(logger.requests[0].request.headers['CustomHeader']).eql(process.env.HEADER_VALUE);
});
Now, you can run tests on the test server with the following command (POSIX):
export HEADER_VALUE='my value'
testcafe chrome test.js
Please refer to this documentation topic for more information: Create a Custom Request Hook.
I have one json file at root:
config.json
{ "base_url": "http://localhost:3000" }
and in my service class, I want to use it in this way:
private productsUrl = config.base_url + 'products';
I've found a ton of posts with either solutions that require a http.get request to load that one file to get that one variable or outdated solutions for angular.js (angular 1)
I cant believe there isnt an easier way to include this file that we already have in place without having to make an additional request to the server.
In my opinion, I would have expected that at least the bootstrapping function would be able to provide this kind of functionality, something like:
platformBrowserDynamic().bootstrapModule(AppModule, { config: config.json });
btw, this works, but its not the ideal solution:
export class Config {
static base_url: string = "http://localhost:3004/";
}
and the use it where you need it:
private productsUrl = Config.base_url + 'products';
Its not ideal, because I will have to create the class (or replace properties) in a build script. (exactly what I was thinking to do with the config.json file).
I still prefer the config.json file approach, since it would not be intrusive with the TypeScript compiler. Any ideas how to do are welcome and really appreciated!
This link explains how to use System.js to load json files in an angular app.
Special thanks to #eotoole that pointed me in the right direction.
If the link above is not clear enough, just add a map into the System.js conf. like this:
map: { 'plugin-json': 'https://unpkg.com/systemjs-plugin-json' }*
*(using external package)
or
map: { 'plugin-json': 'plugin-json/json.js' }**
**if you download the plugin from:
official system.js plugin
now I can use:
const config = require('./config.json');
anywere in my app.
and since it is official from the "systemjs" - guys, I feel comfortable using it to load app settings like base_url or other endpoints.
Now I need to figure out how to encapsulate this logic for testing purposes. Maybe requiring the file in its own class and replacing the values for the specific test case.
Are you using webpack? If you are, and you can just do
const config = require('./config.json');
#Injectable()
export class MyService {
private config:any = config;
....
}
in your webpack config you will need the json-loader
...
module: {
...
loaders: [
...
{
test: /\.json$/,
loaders: ["json-loader"]
},
...
]
}
...
I'm working on a project where various tables of data will be displayed with AngularJS. The data will be in the Collection+JSON format, as shown below. I found this library https://github.com/Medycation/angular-collection-json, I'm not sure how to make it work. Below is an example of the data.
angular.module('app', ['cj']);
var $injector = angular.injector();
var cj = $injector.get('cj');
cj("cjapi1.php").then(function(cjProvider){
console.log(collection.items());
});
I tried the above. In the console it says I need to register cjProvider as a provider. Any help with how to set this up properly would be appreciated. Thanks.
{
“collection”:
{
“version”: “0.1”,
“href” : “https://example.com/companies”
“items” : [
{
“href” : “https://example.com/companies/123”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 1”}
}
},
{
“href” : “https://example.com/companies/1234”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 2”}
}
},
]
}
Please configure your cjProvider while configuring your module. Check the below code template for the reference to configure cjProvider.
angular.module('app', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});
Please make sure that you have configured your transformUrl just shown above.
Your base url must be configured in cjProvider and while hitting any url ang getting data you should transform your request like here you are requesting cjapi1.php. so your baseurl must be append before that like your_base_url + 'cjapi1.php' this will be done for all requesting api. So cjProvider will take care that and will return api path and in .then(responce) you will get your responce which is collection.
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
Are you trying to configure or get the contents of the collection from php call?
Looks like a typo to me but try this to get collection:
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
...and this for configuration of your provider:
angular.module('agile', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});