Search code examples
angularjsfile-uploadprotractorng-file-upload

Unable to upload the image in protractor


Facing following error:

Failed: No element found using locator: By(css selector, input[type="images"])

Protractor code:

it("image upload",function(){
    browser.ignoreSynchronization = true;
    browser.sleep(4000);
    element( by.css('[ng-click="imagePost()"]') ).click();
    browser.sleep(3000);
    var ele = element(by.model("files")).click();
    browser.wait(EC.visibilityOf(ele),8000,'Ele is not presented');

    var fileToUpload = "C:\Users\Shiva\Desktop\mdkg.jpg;"
    console.log(fileToUpload);
    var absolutePath = path.resolve(fileToUpload);
    console.log(absolutePath);
    $('input[type="images"]').sendKeys(absolutePath);
    element(by.buttonText('Post Image')).click();
    browser.sleep(5000);
});

HTML code to upload image:

    <div ngf-drop ng-model="files" ngf-pattern="image/*" data-ngf-multiple="true" ng-repeat="image in images1" ngf-size>
        <img  src="{{image}}" width = "100%" height = "100%" class="m-l img-responsive img-rounded m-b" alt="post images">
        </img-crop>
        <span ng-show="loading" class="text-center col-xs-12" ></span>
    </div>
</div>
<div class="modal-actions ">
    <button type="submit " class="btn-link modal-action ">
        <strong><span class="icon icon-user "></span>postImg</strong>
    </button>
    <button type="button" id="fileinput"   ng-model="files" ngf-select accept="image/* " data-ngf-multiple="true" class="btn-link modal-action">Upload Image

Here I am uploding image, when I click on upload image it navigates to local system and it should upload the image. And after uploading it should post.


Solution

  • here is my answer using page objects:

    this.uploadImage = function(){
    
    var path = require('path');
            var remote = require('../../../../node_modules/protractor/node_modules/selenium-webdriver/remote');
            browser.setFileDetector(new remote.FileDetector());
    
    
            var fileToUpload = '../../mdkg.jpg';
            var absolutePath = path.resolve(__dirname, fileToUpload);
    
            var fileElem = element(by.css('input[type="file"]'));
    
                // Unhide file input
            browser.executeScript("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px';  arguments[0].style.opacity = 1", fileElem.getWebElement());
    
            fileElem.sendKeys(absolutePath);
    
                // take a breath 
            browser.sleep(4000);
            element(by.buttonText('Post Image')).click();
            browser.sleep(4000);
        };
    
    post_text.uploadImage();