I have this URL :
https://www.acme.com/book/passengers?id=h1c7cafc-5457-4564-af9d-2599c6a37dde&hash=7EPbMqFFQu8T5R3AQr1GCw>msearchtype=City+Break
and want to store these values :
id=h1c7cafc-5457-4564-af9d-2599c6a37dde
hash=7EPbMqFFQu8T5R3AQr1GCw
for use in a later test.
How do I extract these values from the URL? I am using Cypress. Thanks.
Please follow the following steps and that's all there is to it.
You can put this snippet into before() hooks of your spec file and you can access them wherever you want.
cy.location().then(fullUrl => {
let pathName = fullUrl.pathname
let arr = pathName.split('?');
let arrayValues = arr[1].split('&');
cy.log(arrayValues[0]);
cy.log(arrayValues[1]);
cy.log(arrayValues[2]);
})
In case anyone needs the correct answer, use the cy.location('search') to extract the search part of the location data.
Then for convenience, convert it to a javascript object with key/value pairs for each item.
Finally, store it in a Cypress alias to use later in the test.
cy.location('search')
.then(search=> {
const searchValues = search.split('?')[1].split('&')
// yields: [
// id=h1c7cafc-5457-4564-af9d-2599c6a37dde,
// hash=7EPbMqFFQu8T5R3AQr1GCw,
// gtmsearchtype=City+Break
// ]
const searchMap = searchValues.reduce((acc,item) => {
const [key,value] = item.split('=')
acc[key] = value.replace('+', ' ')
return acc
}, {})
// yields: {
// id: "h1c7cafc-5457-4564-af9d-2599c6a37dde",
// hash: "7EPbMqFFQu8T5R3AQr1GCw",
// gtmsearchtype: "City Break"
// }
cy.wrap(searchMap).as('searchMap')
})
Using #Srinu Kodi's answer I got it working changing ...then(fullUrl => ... to
...then((fullUrl) => ...
Related
I want to be able ro read json format based on parameter value selected in choice. e.g If dev is selected, it should select (dev1,dev2,dev3) and loop through each selected in json through the node. what is important now is to get the value in json to a file and then I call call it from file into the node
error:
groovy.lang.MissingMethodException: No signature of method: net.sf.json.JSONObject.$() is applicable for argument types: (org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [org.jenkinsci.plugins.workflow.cps.CpsClosure2#7e1eb88f]
Possible solutions: is(java.lang.Object), any(), get(java.lang.Object), get(java.lang.String), has(java.lang.String), opt(java.lang.String)
script in pipeline
#!/usr/bin/env groovy
node{
properties([
parameters([
choice(
name: 'environment',
choices: ['','Dev', 'Stage', 'devdb','PreProd','Prod' ],
description: 'environment to choose'
),
])
])
node () {
def myJson = '''{
"Dev": [
"Dev1",
"Dev2",
"Dev3"
],
"Stage": [
"Stage1",
"Stage2"
],
"PreProd": [
"Preprod1"
],
"Prod": [
"Prod1",
"Prod2"
]
}''';
def myObject = readJSON text: myJson;
echo myObject.${params.environment};
// put the list of the node in a file or in a list to loop
}
Using Pipeline Utility Steps, it can be easier:
Reading from string:
def obj = readJSON text: myjson
Or reading from file:
def obj = readJSON file: 'myjsonfile.json'
Now you can get the element and iterate the list:
def list = obj[params.environment]
list.each { elem ->
echo "Item: ${elem}"
}
Reference: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace
Let me make it simple.
To read the json file you need to download it from git or wherever you stored it. Let's assume git in this case. Once the json file is downloaded then you want to access the content of json file in your code. Which can be done by this code.
import groovy.json.JsonSlurperClassic
def downloadConfigFile(gitProjectURL, jsonnFileBranch) {
// Variables
def defaultBranch = jsonnFileBranch
def gitlabAdminCredentials = 'admin'
def poll = false
def jenkinsFilePath = 'jenkins.json'
// Git checkout
git branch: defaultBranch, credentialsId: gitlabAdminCredentials, poll: poll, url: gitProjectURL
// Check if file existed or not
def jenkinsFile = fileExists(jenkinsFilePath)
if (jenkinsFile) {
def jsonStream = readFile(jenkinsFilePath)
JsonSlurperClassic slurper = new JsonSlurperClassic()
def parsedJson = slurper.parseText(jsonStream)
return parsedJson
} else {
return [:]
}
}
Now we have the entire json file parsed using above function.
Now you can call the function and read the value in a global variable.
stage('Download Config') {
jsonConfigData = downloadConfigFile(gitProjectURL, jsonnFileBranch)
if (jsonConfigData.isEmpty()) {
error err_jenkins_file_does_not_exists
} else {
println("jsonConfigData : ${jsonConfigData}")
}
Now you can access the value of json file or say variable like this.
def projectName = jsonConfigData.containsKey('project_name') == true ? jsonConfigData['project_name'] : ''
You can access any thing if its child node in similar way. I hope it helps you.
it seems to have the same value with matcher but still can't pass the test probably cuz of the memory address stuff. can anyone let me know how i can test the result when a list is in Either<< Right >>
test('get board list from remote data source', () async {
when(mockBoardRemoteDataSource.getBoards())
.thenAnswer((_) async => tBoardModels);
final result = await repository.getBoards();
verify(mockBoardRemoteDataSource.getBoards());
expect(result, equals(Right(toBoards)));
// Either<Failure, List<BoardInfo>> result;
// (new) Right<dynamic, List<BoardInfo>> Right(List<BoardInfo> _r)
});
//console result
Expected: Right<dynamic, List<BoardInfo>>:<Right([_$_BoardInfo(1, name1, address1), _$_BoardInfo(2, name2, address2)])>
Actual: Right<Failure, List<BoardInfo>>:<Right([_$_BoardInfo(1, name1, address1), _$_BoardInfo(2, name2, address2)])>
package:test_api expect
package:flutter_test/src/widget_tester.dart 455:16 expect
test\features\nurban_honey\data\repositories\board_repository_impl_test.dart 58:9 main.<fn>.<fn>.<fn>
//BoardInfo Implementation
import 'package:equatable/equatable.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'board_info.freezed.dart';
#freezed
class BoardInfo extends Equatable with _$BoardInfo {
BoardInfo._();
factory BoardInfo(int id, String name, String address) = _BoardInfo;
#override
List<Object?> get props => [id, name, address];
}
Thanks to Jay, his answer helps me to made my resolution.
This is how i made the test act:
// Act
var results = (await repository.fetch()).fold(
(failure) => failure,
(response) => response,
);
Then I made a type expectation, matching to the failure type declared on my use case:
In the case of the successful execution
// Assert
expect(results, isA<ResultType>());
In the case of the failure expectation
// Assert
expect(results, isA<FailureType>());
The entire test case looks like the following
test('On successful execution, should returns a SuccessResultType', () async {
// Arrange
repository = MyUseCaseRepository();
// Act
var results = (await repository.fetch()).fold(
(failure) => failure,
(response) => response,
);
// Assert
expect(results, isA<SuccessResultType>());
});
I hope this approach can help anybody!
I've made the test pass by doing this:
result.fold(
(l) => null,
(resultR) => Right(toBoards)
.fold((l) => null, (matcherR) => expect(resultR, matcherR)));
is there better way to do it?
I have a utility command in cypress:
Cypress.Commands.add('generateDummyText', (length: number, delay?: number) => {
const wordLength = 5;
const lorem = new LoremIpsum({
wordsPerSentence: {
max: wordLength,
min: wordLength,
},
words: ['word1', 'word2', 'word3', 'word4', 'word5'],
});
const words = lorem.generateWords(Math.ceil(length / wordLength));
cy.wrap(words).as('dummyText');
});
it('test', () => {
// Generate dummy text
cy.generateDummyText(280);
// I want to type the "dummyText variable here"
cy.get('myinput').type()
});
How can this be done? I don't need to use a custom cypress command, but I'd prefer to use one. Looking forward to your reply!
You can access it just by using:
cy.type(this.dummyText)
Another option is just to use faker to generate the random words for you.
Add the faker module to you project, then you can just do:
const faker = require("faker");
.type(faker.random.words(5));
instead of using a custom command for it
You can get the value either by alias:
cy.generateDummyText(280);
cy.get("#dummyText").then(dummyText => {
cy.get('myinput').type(this.dummyText)
})
or directly by the command return value:
cy.generateDummyText(280).then(dummyText => {
cy.get('myinput').type(this.dummyText)
})
I'm doing an app using Laravel inertia and Vue, we wanted to add i18n to the app and use the same translation files for both laravel and i18n, the problem is the variable interpolation, laravel by default use :variable but vue i18n use {variable}
I tried to create a custom formatter based on what i've found here but using a custom formatter seems deprecated since I have this in my console: [intlify] Not supported 'formatter'.
I've seen on the official i18n doc that i18n is supposed to have an option for both prefix and suffix for the variable interpolation but it does not seems to exists in vue-i18n.
Does anyone ever experienced this or have an idea to solve this 'issue' ?
I run a for loop in my translation jsons and converted :variable syntax to {variable}
import {createI18n} from 'vue-i18n'
import zhCN from '../lang/zh-CN.json';
export function initializeI18n() {
let en = {};
Object.entries(zhCN).forEach(([key, value]) => {
let newEnValue = key;
en[key] = key;
if (value.includes(':')) {
let arr = value.match(/\B\:\w+/ig);
arr.forEach(matchedStr => {
let cleanMatchedStr = matchedStr.replace(':', '')
value = value.replace(matchedStr, `{${cleanMatchedStr}}`)
newEnValue = newEnValue.replace(matchedStr, `{${cleanMatchedStr}}`)
})
zhCN[key] = value;
en[key] = newEnValue;
}
})
return createI18n({
locale: window.__DEFAULT_LOCALE__,
fallbackLocale: window.__FALLBACK_LOCALE__,
messages: {
'zh-CN': zhCN,
en
},
silentFallbackWarn: true,
silentTranslationWarn: true
});
}
This was, putting in es.js
"Hello :name": "Hola :name"
should work as expected:
{{ $t("Hello :name", {name: 'world'}) }},
I can't figure out why Jasmine is claiming that the function I'm spying on isn't being called, especially since it is logging in buildLinksObj when called through and not calling when I remove .and.callThrough() I feel like I've written similar code a bunch of times before without any problem. I'm using Jasmine 2.9
The error message I'm getting is:
1) addToLinks should call buildLinksObj if its given an object with children
it should add the personalized links to PageApp.meta.analytics.links
Expected spy buildLinksObj to have been called.
at UserContext.<anonymous> (http://localhost:9877webpack:///tests/specs/common/FetchPersonalContent.spec.js:854:0 <- tests/app-mcom.js:104553:48)
Here's the except of my code:
FetchPersonalContent.js
const buildLinksObj = (responseObj = {}, targetObj, PageApp) => {
console.log('it logs in buildLinksObj') // This is logging!
}
const addToLinks = (responseArr, personalizedLinks) => {
responseArr.forEach((media) => {
const type = media.type;
const typeObj = media[type];
buildLinksObj(typeObj, personalizedLinks, PageApp);
if (typeObj && typeObj.children) {
console.log('has children!')
console.log('typeObj.children is: ', typeObj.children);
typeObj.children.forEach((child) => {
console.log('has a child')
buildLinksObj(child, personalizedLinks, PageApp);
console.log('buildLinksObj was definitely called. what the heck?')
});
}
});
}
export {buildLinksObj, addToLinks, FetchPersonalContent as default,
};
FetchPersonalContent.spec.js
import * as FetchPersonalContent from '../../../src/FetchPersonalContent'; // my path is definitely correct
describe('it should add the personalized links to PageApp.meta.analytics.links', () => {
it('addToLinks should call buildLinksObj if its given an object with children ', () => {
spyOn(FetchPersonalContent, 'buildLinksObj').and.callThrough();
FetchPersonalContent.addToLinks([{
"personalId": 30718,
"type": "carousel",
"carousel": {}
}], {});
expect(FetchPersonalContent.buildLinksObj).toHaveBeenCalled();
});
});
I'd really appreciate any help!
I have a feeling FetchPersonalContent.buildLinksObj in the spec file is not pointing to the same instance as buildLinksObj in the FetchPersonalContent.js file.
Why is export {FetchPersonalContent as default} required? I am assuming you have shared the complete content of FetchPersonalContent.js in your question.
Possible solutions:
You can try removing FetchPersonalContent from the export statement.
Or
Instead of
export {buildLinksObj, addToLinks, FetchPersonalContent as default,
};
You can directly export the constants in FetchPersonalContent.js file.