Uploading image [Cypress] - automation

I'm trying to upload a jpeg image from local files to a webpage developed here in my job. The thing is, we need to click on the page to open the file explorer and then select the image (or drag and drop into the same spot that may be clicked).
Here is a picture from the web page
I don't know how could i do that, i was trying some code that i've seen in "https://medium.com/#chrisbautistaaa/adding-image-fixtures-in-cypress-a88787daac9c". But don't worked. I actually don't know how it works exactly, could anyone help me?
Here is my code
After #brendan's help, I was able to solve the problem by finding an input that was "hidden" under an element. However, before that I tried drag-n-drop, and cypress returned me an error (despite the successful upload). The context was, immediately after the upload, the element re-renders and cypress told me that:
.
Beside the success with input element, i was wondering how it would be possible to resolve this error, is it possible to do something internally to cypress to ignore or wait until the element re-renders back to normal?
Solutions suggested by cypress:

We're doing this using cypress-file-upload
Here's an example from our code:
cy.fixture(fileName).then(fileContent => {
cy.get(selectors.dropZoneInput).upload(
{ fileContent, fileName, mimeType: "application/pdf" },
{ subjectType: "drag-n-drop" }
);
});
For your purpose, I think this will work:
cy.fixture(imagePath).then(fileContent => {
cy.get(".upload-box").first().upload(
{ fileContent, fileName, mimeType: "image/jpeg" },
{ subjectType: "drag-n-drop" }
);
});

Related

Image require() in nuxt with hot reload by HRM webpack

I use the dynamic source for vue-webpack images in nuxt :src="require('path/to/image' + dynamic.variable)" in my project navbar. If the users substitute their image through a form which refetches their information and deletes their previous image I get a webpack error module (img) not found (it does not find the new one): is there a way to solve this, like wait for webpack HRM to finish?
I tried setting up a setTimeout() of one second before user re-fetch and it works, but I don't like a random waiting, I'd use a promise or a sync dynamic, the point is webpack hot reload is not controlled by my functions.. I also tried with setting the dynamic path as a computed: but it doesn't fix.
My image tag:
<img v-if="this.$auth.user.image" class="userlogo m-2 rounded-circle" :src="require('#assets/images/users/' + this.$auth.user.image)" alt="usrimg">
My Useredit page methods:
...
methods: {
userEdit() {
//uploads the image
if (this.formImageFilename.name) {
let formImageData = new FormData()
formImageData.append('file', this.formImageFilename)
axios.post('/db/userimage', formImageData, { headers: { 'Content-Type': 'multipart/form-data' } })
// once it has uploaded the new image, it deletes the old one
.then(res=>{this.deleteOldImage()})
.catch(err=>{console.log(err)})
}else{
this.userUpdate() //if no new image has to be inserted, it proceeds to update the user information
}
},
deleteOldImage(){
if(this.$auth.user.image){axios.delete('/db/userimage', {data: {delimage: this.$auth.user.image}} )}
console.log(this.$auth.user.image + ' deleted')
this.userUpdate() // it has deleted the old image so it proceeds to update the user information
},
userUpdate(){
axios.put(
'/db/user', {
id: this.id,
name: this.formName,
surname: this.formSurname,
email: this.formEmail,
password: this.formPassword,
image: this.formImageFilename.name,
})
.then(() => { console.log('User updated'); this.userReload()}) // reloads the updated user information
.catch(err => {console.log(err)} )
},
userReload(){
console.log('User reloading..')
this.$auth.fetchUser()
.then(() => { console.log('User reloaded')})
.catch(err => {console.log(err)} )
},
}
...
the problem happens after "console.log('User reloading..')" and before "console.log('User reloaded');", it is not related to the file upload nor the server response. I broke a single function in many little ones just to check the function progression and its asynchronous dynamics but the only one that is not manageable is the webpack hot reload :/
I'd like the users to upload their images and see their logo in the Navbar appear updated after submitting the form.
First of all, as somebody told you in the comments, webpack hmr shouldn't be used for production.
In Nuxt, everything that you reference from the assets folder will be optimized and bundled into the project package. So the ideal use case for this folder is all assets that can be packaged and optimized, and most likely won't change like fonts, css, background images, icons, etc.
Then, require is called only once by webpack when it is either building the site for local development or building the site for generating a production package. The problem in your case is that you delete the original file while you're in development and webpack tries to read it and fails.
In the case of these images that the user uploads, I think you should use the static folder instead and instead of using require you'll have to change the :src with
:src="'/images/users/' + this.$auth.user.image"
Let me know if this helps.
Okay, I probably solved it.
HMR: you are of course right. Thank you for pointing out, I am sorry, I am a beginner and I try to understand stuff along the way.
Aldarund, thank you, your idea of not changing the path and cache it client side.. I am too noob to understand how I could implement it ( :) ) but it gave me a good hint: the solution was to keep the image name as the user id + the '.png' extension and to manage the image with jimp so that the image name, extension and file type are always the same, and with or without webpack compiling the new path, I always have the correct require().
Jair, thank you for the help, I didn't follow that road, but I will keep it as a second chance if my way creates errors. Just to be specific: the error comes when it does not find -and asks for the name of- the NEW image, not the OLD one, as I wrote in my question: it happens because the fetchUser() functions reloads the user information including the new image name.
Do you guys see any future problems in my methodology?
Really thank you for your answers. I am learning alone and it's great to receive support.

Show Print and Save Image option using ActionSheetIOS.showShareActionSheetWithOptions

I am trying to implement ActionSheetIOS.showShareActionSheetWithOptions, I am passing the correct url which might be a link to an image or a file(pdf/msword).
I want to provide an option to Print the file or Save Image file when the user clicks on the Share button. But I only see the following options
"Add to reading list", "Copy" and more
Here's my code:
ActionSheetIOS.showShareActionSheetWithOptions({
url: route.passProps.url,
},
(error) => alert(error),
(success, method) => { }
);
I have verified that the url is correct.
When visiting a url, Safari does provide you an option to Print/Save, so I know its possible, but I don't know how.

Notification.Icon loading .png and url fine, but not local file

I'm more trying to understand this than anything, I am not sure if there is an actual solution.
I am using the Notification API (https://developer.mozilla.org/en-US/docs/Web/API/notification) and more specifically this is about the icon property in conjunction with Electron.
I am trying to build a custom notification balloon on Mac and Windows. Everything seems to be pretty straight forward and work, besides the icon part.
This is the issue i am facing (I have verified the file paths exist):
option 1, icon.png (works):
var myNotificiation = new Notification(
title, {
body: message,
icon: jetpack.path(__dirname, 'assets', 'icon.png')
});
option 2, URL (works):
var myNotificiation = new Notification(
title, {
body: message,
icon: "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcR1zOS6CtRHjyHhgclhEKRZ_ipCGU2VCthotUjPp7ErPvSnWb6zZ9fNlA"
});
option 3, local html file (doesn't work):
var myNotificiation = new Notification(
title, {
body: message,
icon: jetpack.path(__dirname, 'services', 'icon.html')
});
For consistency, this is the content of the icon.html page: http://imgur.com/9qkAHky
Question:
Why does the image of the local file jetpack.path(__dirname, 'services', 'icon.html') not populate the icon part of the notification, but the URL image does show up in that same spot?
Any help would be appreciated. I hope its just something simply wrong in my HTML page, but I couldn't find anything wrong yet.
Thanks to Vadim Macagon:
The URL links directly to an image, not an html document, which is consistent with the description of the icon parameter: The icon read-only property of the Notification interface contains the URL of an icon.
This worked for me (source:
https://github.com/electron/electron/issues/1025#issue-54722118)
new Notification({
title: "Message",
body: msg,
icon:'electronImages/hi.png'
}).show()

Navigating site (including forms) with PhantomJS

I'm trying to automate an application that uses form security in order to upload a file and then scrape data from the returned HTML.
I started out using the solution from this question. I can define my steps and get through the entire workflow as long as the last step is rendering the page.
Here are the two steps that are the meat of my script:
function() {
page.open("https://remotesite.com/do/something", function(status) {
if ('success' === status) {
page.uploadFile('input[name=file]', 'x.csv');
page.evaluate(function() {
// assignButton is used to associate modules with an account
document.getElementById("assignButton").click();
});
}
});
},
function() {
page.render('upload-results.png');
page.evaluate(function() {
var results = document.getElementById("moduleProcessingReport");
console.log("results: " + results);
});
},
When I run the script, I see that the output render is correct. However, the evaluate part isn't working. I can confirm that my DOM selection is correct by running it in the Javascript console while on the remote site.
I have seen other questions, but they revolve around using setTimeout. Unfortunately, the step strategy from the original approach already has a timeout.
UPDATE
I tried a slightly different approach, using this post and got similar results. I believe that document uses an older PhantomJS API, so I used the 'onLoadFinished' event to drive between steps.
i recomend you use casperjs or if you use PJS's webPage.injectScript() you could load up jquery and then your own script to do form input/navigation.

How can i use the port.postmessage to send info from the background page to the content script in a Google Chrome extension

I've been able to send data from the background page to the content script. but this is done using sendrequest(). I will need to send data back and forth so I'm trying to figure out the correct syntax for using the port.postmessage from background page to content script. I have already read, several times, the google page on Messaging and I don't seem to get it. I even copied the code directly from the page and tested with no result. All I'm trying to do for now is send data from background page to content script using connect as opposed to sendrequest. The response from the content script I will deal with later as code with this response has been the main thorn. I just want to understand the process one step at a time without the extra knowledge of sending a response back.
I'm not sure if this contravenes the rules of this board but can someone PLEASE give me an example of some code to do this (background page and content script excerpt, the background page is the sender).
I've asked for assistance several times on this site only to be told to read the documentation or check out sites I've already visited.
If you just want any example of opening a port from the extension to a content script, here's the simplest I can think of. The background just opens a port and sends "Hello tab!" over the port, and the content script sends a message to the background any time you click on the webpage.
I think this is pretty simple, so I don't know why you are so stressed. Just make sure that the content tab is already listening when the background tries to connect (I do this by waiting until the "complete" event).
manifest.json:
{
"name": "TestExt",
"version": "0.1",
"background_page": "background.html",
"content_scripts": [{
"matches": ["http://localhost/*"], // same as background.html regexp
"js": ["injected.js"]
}],
"permissions": [
"tabs" // ability to inject js and listen to onUpdated
]
}
background.html:
<script>
var interestingTabs = {};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
// same as manifest.json wildcard
if (changeInfo.url && /http:\/\/localhost(:\d+)?\/(.|$)/.test(changeInfo.url)) {
interestingTabs[tabId] = true;
}
if (changeInfo.status === 'complete' && interestingTabs[tabId]) {
delete interestingTabs[tabId];
console.log('Trying to connect to tab ' + tabId);
var port = chrome.tabs.connect(tabId);
port.onMessage.addListener(function(m) {
console.log('received message from tab ' + tabId + ':');
console.log(m);
});
port.postMessage('Hello tab!');
}
});
</script>
injection.js:
chrome.extension.onConnect.addListener(function(port) {
console.log('Connected to content script!');
port.onMessage.addListener(function(m) {
console.log('Received message:');
console.log(m);
});
document.documentElement.addEventListener('click', function(e) {
port.postMessage('User clicked on a ' + e.target.tagName);
}, true);
});
Detailed documentation and easy (the most basic) examples shown in the documentation page.
Plus, a quick search in stackoverflow will allow you to see many similar questions with detailed answers.