testcafe - Source files do not contain valid 'fixture' and 'test' declarations - testing

I'm writing a test in testcafe for the first time, and trying to do a forEach loop in order to iterate various files.
When trying to run the test, getting this error Source files do not contain valid 'fixture' and 'test' declarations.
import testcafe from 'testcafe';
import { promises } from 'fs';
import { parse } from 'node-html-parser';
let specFiles: string[] = [];
fixture ('OpsLevel test cafe reporter').before( async t => {
specFiles = await promises.readdir('./gauge-reports/html-report/specs')
});
specFiles.forEach(specFile => {
test(`Generate testcafe report from ${specFile}`, async t => {
const gaugeReport = await promises.readFile(specFile, {encoding: 'utf8', flag: 'r'});
const parsedReport = parse(gaugeReport);
const structuredText = parsedReport.structuredText;
await t.expect(structuredText.includes('Success Rate 100%')).eql(true);
});
});
Please advise.

Runtime DataSet initialization for data driven tests is not supported. Please refer to the documentation to learn how to properly initialize a dataset.

Related

how to use rollup to parse cucumber feature files and backing step definition files

I have the following rollup plugin that will include .feature files
export const cucumberRollupPlugin: PluginImpl<CucumberOptions> = pluginOptions => {
let options: CucumberOptions = {
...{
include: '**/*.feature',
cwd: process.cwd(),
},
...pluginOptions,
};
let filter = createFilter(options);
let plugin: Plugin = {
name: 'bigtest-cucumber',
async transform(code, id) {
if (!filter(id)) {
return;
}
let parser = new GherkinParser({ code, uri: id, rootDir: options.cwd });
let result = await parser.parse();
let esm = dataToEsm(result, { namedExports: false });
// TODO: add sourcemap support
let transformResult: TransformResult = { code: esm };
return transformResult;
},
};
return plugin;
};
The problem I have is that to make the feature files work, there are step definition files that actually contain the functionality. So a feature file might look like this
Feature: Visit career guide page in career.guru99.com
Scenario: Visit career.guru99.com
Given: I browse to career.guru99.com
And a step definition file might look like this:
import { Given, When, Then from 'cucumber';
import assert from 'assert';
import{ driver } from '../support/web_driver';
Given(/^browse to web site "([^"]*)"$/, async function(url) {
return driver.get(url);
});
The problem I have with rollup is that there are no import statements for either the step definition files. The way cucumber-js works is that these files are found at runtime.
I think I need to generate an index.js that looks like this to cover the step definitions.
import from './step_definition_1';
import from './step_definition_2';
import from './step_definition_3';
Where would this fit in the rollup pipeline to generate this file so it can get pulled into the rollup pipeline.
You can use this.emitFile to manually process the .feature files and include them in the output. Call this.emitFile for each .feature file in the buildStart hook (each emitted file will get processed through the transform hook you wrote).
Here's an example that uses the globby package (which expands a glob to an array of file paths) to get the file path of each .feature file to pass to this.emitFile:
import globby from 'globby'
export const cucumberRollupPlugin: PluginImpl<CucumberOptions> = pluginOptions => {
let options: CucumberOptions = {
include: '**/*.feature',
cwd: process.cwd(),
...pluginOptions,
};
let filter = createFilter(options);
let plugin: Plugin = {
name: 'bigtest-cucumber',
async buildStart({ include, cwd }) {
const featureFilePaths = await globby(include, { cwd });
for (const featureFilePath of featureFilePaths) {
this.emitFile({
type: 'chunk',
id: featureFilePath
});
}
},
async transform(code, id) {
if (!filter(id)) {
return;
}
let parser = new GherkinParser({ code, uri: id, rootDir: options.cwd });
let result = await parser.parse();
let esm = dataToEsm(result, { namedExports: false });
// TODO: add sourcemap support
let transformResult: TransformResult = { code: esm };
return transformResult;
},
};
return plugin;
};
Let me know if you have any questions!
You need to use the this.emitFile method and befor that lookup the files via glob or anything else inside your plugin
{
plugins: [typescript(),{
name: "emit-additional-files",
async transform(code,id) {
//id === fileName
//code === fileContent
// inspect code or id here then use path.resolve() and fs.readdir to find additional files
this.emitFile()
}
}]
}

Mocking runtime config value with sinon

I am adding some config values before hapi server start. Application is works fine although in test I can not use config.get(). I can get around with proxyquire. So I was wondering
Is adding config file "dynamically" is bad design?
Is there a way I can use config.get() in such suitation?
Any alternative approach?
//initialize.js
const config = require('config');
async function startServe() {
const someConfigVal = await callAPIToGetSomeJSONObject();
config.dynamicValue = someConfigVal;
server.start();
}
//doSomething.js
const config = require('config');
function doesWork() {
const valFromConfig = config.dynamicValue.X;
// In test I can use proxiquire by creating config object
...
}
function doesNotWork() {
const valFromConfig = config.get('dynamicValue.X');
// Does not work with sinon mocking as this value does not exist in config when test run.
// sinon.stub(config, 'get').withArgs('dynamicValue.X').returns(someVal);
.....
}
Context: testing.
Is adding config file "dynamically" is bad design? => No. I have done it before. The test code changes configuration file: default.json in mid test to check whether function under test behaves as expected. I used several config utilities.
Is there a way I can use config.get() in such suitation? => Yes. For sinon usage, see the example below, which use mocha. You need to define the stub/mock before the function under test use it, and do not forget to restore the stub/mock. Also there is official documentation related to this: Altering configuration values for testing at runtime, but not using sinon.
const config = require('config');
const sinon = require('sinon');
const { expect } = require('chai');
// Example: simple function under test.
function other() {
const valFromConfig = config.get('dynamicValue.X');
return valFromConfig;
}
describe('Config', function () {
it ('without stub or mock.', function () {
// Config dynamicValue.X is not exist.
// Expect to throw error.
try {
other();
expect.fail('expect never get here');
} catch (error) {
expect(error.message).to.equal('Configuration property "dynamicValue.X" is not defined');
}
});
it('get using stub.', function () {
// Create stub.
const stubConfigGet = sinon.stub(config, 'get');
stubConfigGet.withArgs('dynamicValue.X').returns(false);
// Call get.
const test = other();
// Validate te result.
expect(test).to.equal(false);
expect(stubConfigGet.calledOnce).to.equal(true);
// Restore stub.
stubConfigGet.restore();
});
it('get using mock.', function () {
// Create mock.
const mockConfig = sinon.mock(config);
mockConfig.expects('get').once().withArgs('dynamicValue.X').returns(false);
// Call get.
const test = other();
// Validate te result.
expect(test).to.equal(false);
// Restore mock.
expect(mockConfig.verify()).to.equal(true);
});
});
Hope this helps.

How to check downloaded file name?

I wrote a test that downloads the export file, but I also need to send this file through email. The problem is that filename is always different and I don't know how to look it up during the test.
You can retrieve the dynamic downloaded filename from the 'content-disposition' header.
import { Selector, RequestLogger } from 'testcafe';
const url = 'https://demos.devexpress.com/ASPxGridViewDemos/Exporting/Exporting.aspx';
const logger = RequestLogger({ url, method: 'post' }, {
logResponseHeaders: true
});
fixture `Export`
.page(url)
.requestHooks(logger);
test('export to csv', async t => {
const exportToCSVButton = Selector('span').withText('Export to CSV');
await t
.click(exportToCSVButton)
.expect(logger.contains(r => r.response.statusCode === 200)).ok();
console.log(logger.requests[0].response.headers['content-disposition']);
});
See also: Check the Downloaded File Name and Content

Conditional test to bypass pop up with Testcafe

I'm using testcafe to run some tests in an ecommerce page, but a random pop up is breaking the test. When it appears on the window, the Testcafe is unable to click on the next selector and move forward with the test, and then fail.
Currently, I'm using .js files to hold the selectors, like:
import { Selector } from 'testcafe';
export default class Checkout {
constructor () {
//address
this.addressName = Selector('input#CC-checkoutCepAddressBook-sfirstname');
this.addressLastname = Selector('input#CC-checkoutCepAddressBook-slastname');
//Rest of selectors...
}
Then, I import them to another .js and declare the tests like functions:
import { ClientFunction } from 'testcafe';
import { Selector } from 'testcafe';
import Fixture from '../../../DesktopModel/Chrome/fixture.js';
import Home from '../../../DesktopModel/Chrome/home.js';
import Cart from '../../../DesktopModel/Chrome/cart.js';
...
const fixtureUrlBase = new Fixture();
const home = new Home();
const pdp = new Pdp();
const cart = new Cart();
...
export async function checkoutLoggedBoleto(t) {
await t
.click(pdp.addToCartBtn)
.click(home.finishOrderBtn)
.click(cart.finishOrderBtn)
//Rest of the test actions...}
Finally, I'm executing another.js where I declare the tests using test command:
test
.before(async t => {
await login(t);
})
('Desktop - User Login + Checkout with Invoice', async t => {
// Function Login => Search => PDP => Checkout with Invoice
await checkoutLoggedBoleto(t);
});
Since it is a random event (it happens in different moments, like sometimes in the product page and sometimes in the checkout page), is possible to use some conditional test just bypass this popup, like if the pop up 'x' appears on the screen, click on 'close popup' and continue with test, else continue with the test.
I search in testcafe Test API and have not found such a function.
I'm using testcafe 0.17.0.
TestCafe doesn't provide an API for that. To handle you case, you can check whether the popup appears before each action.
Optionally, to make your code cleaner, you can wrap TestCafe API actions in the following way:
import { t, Selector } from 'testcafe';
const closePopupBtn = Selector('.close-popup');
async function checkPopup () {
if(await closePopupBtn.exists)
await t.click(closePopupBtn);
}
const tc = {
click: async selector => {
await checkPopup();
await t.click(selector);
}
}
test('my test', async () => {
await tc.click('.btn1');
await tc.click('.btn2');
});

How Do I use a node.js module with Next.js?

Do I need to use express with next.js?
Im trying to add this code into a next.js application. ( from npm module example code: pdf2json )
let fs = require('fs');
var PDFParser = require("pdf2json");
let pdfParser = new PDFParser(this,1);
pdfParser.on("pdfParser_dataError", errData =>
console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", pdfData => {
fs.writeFile("./sometxt.txt", pdfParser.getRawTextContent());
pdfParser.loadPDF("./page1.pdf");
You can require it conditionally by testing if it is the server:
static async getInitialProps({isServer}){
var fs;
if(isServer){
fs=require('fs');
//and do what ever you want
}
}
and dot not forgot to tell webpack to do not send the module to the client side by changing package.json like so:
"browser": {
"fs": false
}
unless it can produce errors.
The thing that's probably biting you is that most of your code must work on both the client and the server. You can write server-only code by creating a getInitialProps() method and checking to see if it's passed in a opts.req - if so, you know the code is running server-side and you can hit the filesystem:
import React from 'react'
const doServerSideStuff = () => {
let fs = require('fs');
var PDFParser = require("pdf2json");
let pdfParser = new PDFParser(this,1);
pdfParser.on("pdfParser_dataError", errData =>
console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", pdfData => {
fs.writeFile("./sometxt.txt", pdfParser.getRawTextContent());
pdfParser.loadPDF("./page1.pdf");
}
export default class extends React.Component {
static async getInitialProps ({ req }) {
if (req) {
doServerSideStuff();
}
return {};
}
render () {
return <div> Hello World </div>
}
}
This isn't really a complete example yet, you should really make doServerSideStuff() async (or return a promise) and then await it in getInitialProps, and eventually return props that represent the result of the parsing & saving. Also, handle fs.writeFile errors. But, hopefully it's enough to get you going in the right direction.
See the docs for some more info on this.
Or you could just use Express like you suggested. There is a good tutorial and example code that should help you get started if you decide to go that route.