How to map different JSON objects from the fixture into specific spec test file in the cypress - cypress

I have the below Input.json as fixture and It contains two different test cases.
Input.json (Fixture folder)
[
{
"searchKeyword":"cypress"
},
{
"username":"QATesting",
"password":"testprofile"
}
]
The above data will validate two different functionality of Google. One is going to validate search engine and another one is going to validate the user login activity (This is just for sample use case which may imitate my actual requirement).
I just created the cypress runner and I just want to run the spec file by using the below runner.js file
const cypress = require('cypress')
const fixtures = require('./cypress/fixtures/Test.json')
const promises = fixtures.map(fixture => {
return cypress.run({
env: {
fixture
},
spec: './cypress/integration/test.spec.js',
});
});
I just added two different It(test cases) respectively in the below "test.spec.js" file. And one test is gonna do the search function and another one is gonna check the existing user login activity:
describe("How to map two different data set with respective test function",() =>{
const baseUrl = "https://www.google.com/";
const testData = Cypress.env('fixture')
beforeEach("",()=>{
cy.visit(baseUrl);
});
it("Test Case1: Search the keyword", function () {
cy.xpath("//input[#name='q']").type(testData.searchKeyword);
cy.xpath("//input[#value='Google Search']").click();
cy.get("//ul/li[2]").should("be.visible");
});
it("Test Case2: login to the gmail account", function(){
cy.xpath("//a[contains(text(),'Sign in')]").click();
cy.xpath("//div[contains(text(),'Use another account')]").click();
cy.xpath("#identifierId").type(testData.username);
cy.xpath("//*[contains(text(),'Next')]").click();
cy.xpath("#password").type(testData.password);
cy.xpath("#submitbtn").click();
})
});
But the second test is getting failed and the testData.username return undefined.
Is there anyway to map the specific JSON array object with specific function in the test.spec.js file?
Not sure how to map the first dataset index with first It (Test case 1) and second dataset index with second test case respectively.

One quick way is to skip if the testData does not have the required properties,
describe("How to map two different data set with respective test function",() =>{
const baseUrl = "https://www.google.com/";
const testData = Cypress.env('fixture')
beforeEach("",()=>{
cy.visit(baseUrl);
});
it("Test Case1: Search the keyword", function () {
if (!testData.searchKeyword) this.skip
cy.xpath("//input[#name='q']").type(testData.searchKeyword);
cy.xpath("//input[#value='Google Search']").click();
cy.get("//ul/li[2]").should("be.visible");
});
it("Test Case2: login to the gmail account", function() {
if (!testData.username) this.skip
cy.xpath("//a[contains(text(),'Sign in')]").click();
cy.xpath("//div[contains(text(),'Use another account')]").click();
cy.xpath("#identifierId").type(testData.username);
cy.xpath("//*[contains(text(),'Next')]").click();
cy.xpath("#password").type(testData.password);
cy.xpath("#submitbtn").click();
})
});
Tagging
You can also get into tags, adding a tag property to the testData
[
{
"tag": "search",
"searchKeyword":"cypress"
},
{
"tag": "user",
"username":"QATesting",
"password":"testprofile"
}
]
Perhaps use a library like cypress-tags, then in the runner script
const cypress = require('cypress')
const fixtures = require('./cypress/fixtures/Test.json')
const promises = fixtures.map(fixture => {
if (fixture.tag) {
process.env.CYPRESS_INCLUDE_TAGS = fixture.tag
}
return cypress.run({
env: {
fixture
},
spec: './cypress/integration/test.spec.js',
});
});

Since your fixtures data is in a array and the username and password fields are at index 1, so in order to access those you have to use:
testData[1].username
testData[1].password
In case if you don't want to use the index value, change the fixture structure to:
{
"searchKeyword": "cypress",
"username": "QATesting",
"password": "testprofile"
}
And in your test directly use:
testData.username
testData.password

Related

Cypress how to stored input data and parse for verification

I have a table form at webpage. User filled up and hit upload then result firm is displayed.
Table a input abc
Table b input 123
I want to verify the data is displayed at result page.
How do i store the value abc 123 for verification? To avoid linear coding, i do not want to rewrite those values again and to prevent if test data changed, i just need to change once.
To test the tables/forms, iterate the expected results.
it('tests form', () => {
const expected = [
[ 'a', 'abc' ],
[ 'b', '123' ],
]
expected.forEach(exp => {
cy.get(`table#${exp[0]}`) // construct selector
.find('input')
.invoke('val')
.should('eq', exp[1]) // verify
})
})
You can create a json file and save it under fixtures like data.json:
{
"tableA": {
"name": "table a",
"selector": "input"
"value": "abc",
"checkbox": "be.checked"
},
"tableB": {
"name": "table b",
"selector": "input"
"value": 123,
"checkbox": "not.be.checked"
}
}
And in your tests you can write:
describe('Some page', () => {
beforeEach(function() {
// "this" points at the test context object
cy.fixture('data.json').then((data) => {
this.data = data
})
})
it('has user', function() {
expect(this.data.tableA.name).to.equal('table a')
expect(this.data.tableA.selector).to.equal('input')
expect(this.data.tableA.value).to.equal('abc')
cy.get('selector').should(this.data.tableA.checkbox)
})
})
Important Note:
If you store and access the fixture data using this test context
object, make sure to use function () { ... } callbacks. Otherwise the
test engine will NOT have this pointing at the test context.

How to modify just a property from a dexie store without deleting the rest?

I'm having the dexie stores showed in the print screen below:
Dexie stores print screen
My goal is to update a dexie field row from a store without losing the rest of the data.
For example: when I edit and save the field "com_name" from the second row (key={2}) I want to update "com_name" only and not lose the rest of the properties, see first and the third row.
I already tried with collection.modify and table.update but both deleted the rest of the properties when used the code below:
dexieDB.table('company').where('dexieKey').equals('{1}')
//USING table.update
//.update(dexieRecord.dexiekey, {
// company: {
// com_name: "TOP SERVE 2"
// }
//})
.modify(
{
company:
{
com_name: TOP SERVE 2
}
}
)
.then(function (updated) {
if (updated)
console.log("Success.");
else
console.log("Nothing was updated.");
})
.catch(function (err) { console.log(err); });
Any idea how can I accomplish that?
Thanks
Alex
You where right to use Table.update or Collection.modify. They should never delete other properties than the ones specified. Can you paste a jsitor.com or jsfiddle repro of that and someone may help you pinpoint why the code doesn't work as expected.
Now that you are saying I realised that company and contact stores are created dynamically and editedRecords store has the indexes explicitly declared therefore when update company or contact store, since dexie doesn't see the indexes will overwrite. I haven't tested it yet but I suspect this is the behaviour.
See the print screen below:
Dexie stores overview
Basically I have json raw data from db and in the browser I create the stores and stores data based on it, see code below:
function createDexieTables(jsonData) { //jsonData - array, is the json from db
const stores = {};
const editedRecordsTable = 'editedRecords';
jsonData.forEach((jsonPackage) => {
for (table in jsonPackage) {
if (_.find(dexieDB.tables, { 'name': table }) == undefined) {
stores[table] = 'dexieKey';
}
}
});
stores[editedRecordsTable] = 'dexieKey, table';
addDataToDexie(stores, jsonData);
}
function addDataToDexie(stores, jsonData) {
dbv1 = dexieDB.version(1);
if (jsonData.length > 0) {
dbv1.stores(stores);
jsonData.forEach((jsonPackage) => {
for (table in jsonPackage) {
jsonPackage[table].forEach((tableRow) => {
dexieDB.table(table).add(tableRow)
.then(function () {
console.log(tableRow, ' added to dexie db.');
})
.catch(function () {
console.log(tableRow, ' already exists.');
});
});
}
});
}
}
This is the json, which I convert to object and save to dexie in the value column and the key si "dexieKey":
[
{
"company": [
{
"dexieKey": "{1}",
"company": {
"com_pk": 1,
"com_name": "CloudFire",
"com_city": "Round Rock",
"serverLastEdit": [
{
"com_pk": "2021-06-02T11:30:24.774Z"
},
{
"com_name": "2021-06-02T11:30:24.774Z"
},
{
"com_city": "2021-06-02T11:30:24.774Z"
}
],
"userLastEdit": []
}
}
]
}
]
Any idea why indexes were not populated when generating them dynamically?
Given the JSON data, i understand what's going wrong.
Instead of passing the following to update():
{
company:
{
com_name: "TOP SERVE 2"
}
}
You probably meant to pass this:
{
"company.com_name": "TOP SERVE 2"
}
Another hint is to do the add within an rw transaction, or even better if you can use bulkAdd() instead to optimize the performance.

using a single query to call multiple queries using apollo react hooks

I am new to this graphql, so what i am trying to achieve here is, i need to call two queries parallelly basically combining the queries and get the loading at a single time.
here i have seperated the queries and using two loading state, i need to combine it like compose.
The use case is, user clicks on the button on the button click i will pass the id, and hit both queries and get the list of data
<Button
text="Details"
onClick={() => {
getNames({ variables: { location_id: Number(location_id) } });
getSchools({ variables: { location_id: Number(location_id) } });
}}
>
const [getNames, { loading: namesLoading, data: namesData }] = useLazyQuery(
GET_NAMES
);
const [
getSchools,
{ loading: schoolsLoading, data: schoolsData },
] = useLazyQuery(GET_SCHOOLS);
const GET_NAMES = gql`
query get_names($location_id: Int!) {
get_names(location_id: $location_id) {
id
name
}
}
`;
const GET_SCHOOLS = gql`
query get_schools($location_id: Int!) {
get_schools(location_id: $location_id) {
schools {
id
name
}
}
}
`;
With splitting i am able to see the data, i am using "#apollo/react-hooks" to get the data with useLazyQuery, how can i achieve with this a single query. So instead of multiple loading , error data i can have a single one
Didn't find any compose hook from this library

Correct way to expect/receive state with Enzyme & MockProvider

I'm testing a component that is using a graphql useLazyQuery. MockProvider is provided by the Apollo recommended library #apollo/react-testing. I want to test that a certain message is being rendered base off the length of the data that is returned from the query. I have html elements structured like this:
<div className="message" data-id={props.data ? props.data.specials.length > 0 ? 'valid' : 'invalid' : ''}>
...children
</div>
I read through Apollo's docs about testing and wrote up a test like this:
mock = {
request: {
query: GET_PRODUCTS,
variables: { zip: "91001" }
},
result: {
data: {
specials: [
{
"_id": "5ecf28c459d3781a2e99738e",
},
{
"_id": "5ecf28c459d3781a2e99738f",
}
]
}
}
}
wrapper = mount(
<MockedProvider mocks={[mock]} addTypename={false}>
<Store.Provider value={[{ loading: false, zip: null }]}>
<GetZipCode />
</Store.Provider>
</MockedProvider>
)
await wait(0)
expect(wrapper.find(message).prop('data-id')).toEqual('valid')
But I've found that the tests do not update based on the mock that I put it. I have a test about this where I'm passing this value as the mock:
mock = {
request: {
query: GET_PRODUCTS,
variables: { zip: "32005" }
},
result: {
data: { specials: [] }
}
}
...after tests
expect(wrapper.find(message).prop('data-id')).toEqual('invalid')
And for both of these tests the expected value is "" which is the initial value for my data-id prop in my html element. If I were to set the initial value to "invalid" compared to "" then the expected value in my test would output "invalid".
It seems that no matter what I passed my mock provider it doesn't wait for it to be passed. I'm using the wait package that Apollo recommends as well.
If you wanna mock using jest, you use the following approach
jest.mock("apollo-client", () => ({
__esModule: true,
useQuery: (query: any) => {
//other mocks if needed
},
useLazyQuery: jest.fn().mockReturnValue([
jest.fn(),
{
data: {
yourProperties: "Add Here",
},
loading: false,
},
]),
}));
As you see, this approach even returns the mock function that is called in the code to be tested.
I faced in similar issues while testing with useLazyQuery. I would suggest writing a custom hook on top of useLazyQuery. This will have two benefits:
No need to wrap your test instance in Mock provider. You can mock the entire module (custom hook) using jest and use mockReturnValue method to simulate different behaviours (loading, data, error)
You can easily switch between actual query or some mock data in local file system while development.
Refer this blog for implementation details and demo app.

Perform sequential api calls with RxJs?

Is there a way in RxJs to perform two api calls where the second requires data from the first and return a combined result as a stream? What I'm trying to do is call the facebook API to get a list of groups and the cover image in various sizes. Facebook returns something like this:
// call to facebook /1234 to get the group 1234, cover object has an
// image in it, but only one size
{ id: '1234', cover: { id: '9999' } }
// call to facebook /9999 to get the image 9999 with an array
// with multiple sizes, omitted for simplicity
{ images: [ <image1>, <image2>, ... ] }
// desired result:
{ id: '1234', images: [ <image1>, <image2>, ... ] }
So I have this:
var result = undefined;
rxGroup = fbService.observe('/1234');
rxGroup.subscribe(group => {
rxImage = fbService.observe(`/${group.cover.id}`);
rxImage.subscribe(images => {
group.images = y;
result = group;
}
}
I want to create a method that accepts a group id and returns an Observable that will have the combined group + images (result here) in the stream. I know I can create my own observable and call the next() function in there where I set 'result' above, but I'm thinking there has to be an rx-way to do this. select/map lets me transform, but I don't know how to shoe-in the results from another call. when/and/then seems promising, but also doesn't look like it supports something like that. I could map and return an observable, but the caller would then have to do two subscribes.
Looks like flatMap is the way to go (fiddle). It is called like subscribe and gives you a value from a stream. You return an observable from that and it outputs the values from all the created observables (one for for each element in the base stream) into the resulting stream.
var sourceGroup = { // result of calling api /1234
id: '1234',
cover: {
id: '9999'
}
};
var sourceCover = { // result of calling api /9999
id: '9999',
images: [{
src: 'image1x80.png'
}, {
src: 'image1x320.png'
}]
};
var rxGroup = Rx.Observable.just(sourceGroup);
var rxCombined = rxGroup.flatMap(group =>
Rx.Observable.just(sourceCover)
.map(images => ({
id: group.id,
images: images.images
}))
)
rxCombined.subscribe(x =>
console.log(JSON.stringify(x, null, 2)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.min.js"></script>
Result:
{
"id": "1234",
"images": [
{
"src": "image1x80.png"
},
{
"src": "image1x320.png"
}
]
}
You should use concatMap instead of flatMap, it will preserve the order of the source emissions.

Resources