Read excel files in Cypress - cypress

I am new to Cypress. How to read data from excel files using Cypress? Searched in google but could not find useful answers.

In cypress you can create cypress task to read xlsx file with SheetJS library.
Usage
cypress\integration\read-xlsx.spec.js
context('Xlsx file', () => {
it('Read excel file', () => {
cy.task('readXlsx', { file: 'my-excel.xlsx', sheet: "Sheet1" }).then((rows) => {
expect(rows.length).to.equal(543)
// expect(rows[0]["column name"]).to.equal(11060)
})
})
})
Need to install xlsx
$ npm install xlsx
Create read excel fuction
cypress\plugins\read-xlsx.js
const fs = require('fs');
const XLSX = require('xlsx');
const read = ({file, sheet}) => {
const buf = fs.readFileSync(file);
const workbook = XLSX.read(buf, { type: 'buffer' });
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
return rows
}
module.exports = {
read,
}
Use function as Cypress task (plugin)
cypress\plugins\index.js
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read
})
}

Here is an instruction how to use excel as source for cypress tests https://medium.com/#you54f/dynamically-generate-data-in-cypress-from-csv-xlsx-7805961eff55
First you need to conver your xlsx file to json with Xlsx
import { writeFileSync } from "fs";
import * as XLSX from "xlsx";
try {
const workBook = XLSX.readFile("./testData/testData.xlsx");
const jsonData = XLSX.utils.sheet_to_json(workBook.Sheets.testData);
writeFileSync(
"./cypress/fixtures/testData.json",
JSON.stringify(jsonData, null, 4),
"utf-8"
);
} catch (e) {
throw Error(e);
}
Then import json file and loop over each row and use the data in the way you want. In this example it tries to log in to a system.
import { login } from "../support/pageObjects/login.page";
const testData = require("../fixtures/testData.json");
describe("Dynamically Generated Tests", () => {
testData.forEach((testDataRow: any) => {
const data = {
username: testDataRow.username,
password: testDataRow.password
};
context(`Generating a test for ${data.username}`, () => {
it("should fail to login for the specified details", () => {
login.visit();
login.username.type(data.username);
login.password.type(`${data.password}{enter}`);
login.errorMsg.contains("Your username is invalid!");
login.logOutButton.should("not.exist");
});
});
});
});

For me the first answer pretty much worked. But i had to make a small fix.
Use function as Cypress task (plugin)
cypress/plugins/index.js
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read
})
}
when i used this code i got the below error in cypress.
CypressError
cy.task('log') failed with the following error:
The task 'log' was not handled in the plugins file. The following tasks are registered: readXlsx
and the below fix worked
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read,
log (message) {
console.log(message)
return null
}
})
}

Related

Cypress - How can I add assertion for downloaded file contains name that is dynamic?

In cypress, the xlsx file I am downloading always starts with lets say "ABC" and then some dynamic IDs like ABC86520837.xlsx. How can I verify and add assertion that if the file is downloaded successfully and also contains that dynamic name?
You'll need to create a task to search within file directory of your machine and then return a list of matching downloads to assert. You'll also need globby to make it easier.
In your plugins/index.js
async findFiles (mask) {
if (!mask) {
throw new Error('Missing a file mask to search')
}
console.log('searching for files %s', mask)
const list = await globby(mask)
if (!list.length) {
console.log('found no files')
return null
}
console.log('found %d files, first one %s', list.length, list[0])
return list[0]
},
In your spec file:
const downloadsFolder = Cypress.config('downloadsFolder')
const mask = `${downloadsFolder}/ABC*.xlsx`
cy.task('findFiles', mask).then((foundImage) => {
expect(foundImage).to.be.a('string')
cy.log(`found image ${foundImage}`)
})
Cypress example
Assuming you are running a recent version of Cypress,
Add a task to read the downloads folder in /cypress.config.js
const { defineConfig } = require('cypress')
const fs = require('fs')
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
filesInDownload (folderName) {
return fs.readdirSync(folderName)
},
})
}
}
})
In the test
const downloadsFolder = Cypress.config('downloadsFolder')
cy.task('filesInDownload', downloadsFolder).then(files => {
const abcFile = files.find(file => file.startsWith('ABC'))
expect(abcFile).to.not.be.undefined
})
I recommend you set the downloadsFolder configuration, as this will remove files between test runs.

Cannot find module babel-preset-es2015 in cypress

The erros occurs when i add
const replace = require("replace-in-file"); in file to my code
const replace = require("replace-in-file");
const options = {
files: "./config/dashboardData.json",
configFile: true,
from: /}\n{/g,
to: ",\n",
};
I have installed babel and configured the preset still I got the issue
The package replace-in-file handles files on the OS, so it needs to be called from Node.
You would need to set up a Cypress task.
In Cypress ver 10+, do this in cypress.config.js
// cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
replaceTask(options) {
const replace = require("replace-in-file");
try {
const results = replace.sync(options);
return results
}
catch (error) {
return error
}
},
})
},
// other e2e configuration here
},
});
// test.spec.cy.js
it('calls replace-in-file', () => {
const options = {
files: "./config/dashboardData.json",
configFile: true,
from: /}\n{/g,
to: ",\n",
};
cy.task('replaceTask', options).then(resultsOrError => {
console.log(resultsOrError)
})
});

Heroku Error: ENOENT: no such file or directory, stat '/app/build/index.html'

I am getting this error in my heroku logs.
Same Question
All the solutions provided here did not address the issue.
I tried the different variations of the get method:
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
What else could I try or am I missing from here?
App.js
const configuration = require('#feathersjs/configuration');
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const moment = require('moment');
class IdeaService {
constructor() {
this.ideas = [];
}
async find() {
return this.ideas;
}
async create(data) {
const idea = {
id: this.ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
this.ideas.push(idea);
return idea;
}
}
const app = express(feathers());
app.feathers().configure(configuration());
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
// Parse JSON
app.use(express.json());
// Configure SocketIO realtime API
app.configure(socketio());
// Enable REST services
app.configure(express.rest());
// Register services
app.use('/ideas', new IdeaService());
// Connect new streams
app.on('connection', conn => app.channel('stream').join(conn));
// Publish events to stream
app.publish(data => app.channel('stream'));
const PORT = process.env.PORT || 3030;
app.listen(PORT).on('listening', () => console.log(`Server running on port ${PORT}`));
app.service('ideas').create({
text: 'Build a cool app',
tech: 'Node.js',
viewer: 'John Doe'
});
export default IdeaService;
package.json

how can i upload file by using xpath in cypress

How can upload file by using xpath in cypress?
Am getting as mentioned below error...
const xpath = require('cypress-xpath')
describe('File upload Demo', () => {
Cypress.Commands.add('uploadFile', { prevSubject: 'element' }, (subject, fileName) => {
console.log('subject', subject)
return cy.fixture(fileName, 'base64')
.then(Cypress.Blob.base64StringToBlob)
.then(blob => {
console.log('blob', blob)
const el = subject[0]
if (el != null) {
const testFile = new File([blob], fileName)
const dataTransfer = new DataTransfer()
dataTransfer.items.add(testFile)
el.files = dataTransfer.files
}
return subject
})
}
)
it('upload file test', () => {
cy.visit('https://tus.io/demo.html')
cy.xpath('//input[#type="file"]').upload('401k_deferral.xlsx')
cy.get('[class="button primary"]').should('have.class', 'button primary')
})
})
TypeError: cy.xpath(...).upload is not a function
The custom command you have added is called uploadFile but you are trying to call upload.
Try this:
cy.xpath('//input[#type="file"]').uploadFile('401k_deferral.xlsx')

How to Unit Test Graphql Resolver functions created using apollo-resolvers

I have created resolvers(userresolver.js) using 'apollo-resolvers' npm module as below.
import { createResolver } from 'apollo-resolvers';
import { isInstance } from 'apollo-errors';
const baseResolver = createResolver(
null,
(root, args, context, error) => isInstance(error) ? error : new UnknownError()
);
const users = baseResolver.createResolver(
(parent, args, { models, me } ) => {
return Object.values(models.users);
}
);
export default {
Query: {
users
}
}
;
These also work fine when I test the queries after starting the server.
I now want to do unit testing of the resolver functions.
I am not sure how to do that. Can someone help me on how to unit test the resolver functions. I am using mocha with chai for testing my project.
You can try easygraphql-tester, it has a method that'll help you to test the resolvers.
Here is the documentation of it.
Example:
Resolver
"use strict";
const license = (__, args, ctx) => {
const { key } = args;
return {
id: "1234",
body: "This is a test license",
description: `This is a description with key ${key}`
};
};
module.exports = {
Query: {
license
}
};
Test
"use strict";
const fs = require("fs");
const path = require("path");
const { expect } = require("chai");
const EasyGraphQLTester = require("easygraphql-tester");
const resolvers = require("../resolvers");
const schemaCode = fs.readFileSync(
path.join(__dirname, "..", "schema.gql"),
"utf8"
);
describe("Test resolvers", () => {
let tester;
beforeAll(() => {
tester = new EasyGraphQLTester(schemaCode, resolvers);
});
it("should return expected values", async () => {
const query = `
query GET_LICENSE($key: String!) {
license(key: $key) {
id
body
description
}
}
`;
const args = {
key: "1234"
};
const result = await tester.graphql(query, {}, {}, args);
expect(result.data.license.id).to.be.eq("1234");
expect(result.data.license.body).to.be.eq("This is a test license");
expect(result.data.license.description).to.be.eq(
`This is a description with key ${args.key}`
);
});
});

Resources