How to use updateContainer method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

script.js

Source: script.js Github

copy
1const fetchAllButton = document.getElementById("fetch-quotes");
2const fetchRandomButton = document.getElementById("fetch-random");
3const fetchByAuthorButton = document.getElementById("fetch-by-author");
4const updateById = document.getElementById("update-by-id")
5
6const quoteContainer = document.getElementById("quote-container");
7const quoteText = document.querySelector(".quote");
8const attributionText = document.querySelector(".attribution");
9
10const updateContainer = document.querySelector(".request-buttons");
11const idTextField = document.getElementById("identification");
12
13const resetQuotes = () => {
14  quoteContainer.innerHTML = "";
15};
16
17const renderError = (response) => {
18  quoteContainer.innerHTML = `<p>Your request returned an error from the server: </p>
19<p>Code: ${response.status}</p>
20<p>${response.statusText}</p>`;
21};
22
23const renderQuotes = (quotes = []) => {
24  resetQuotes();
25  if (quotes.length > 0) {
26    quotes.forEach((quote) => {
27      const newQuote = document.createElement("div");
28      newQuote.className = "single-quote";
29      newQuote.innerHTML = `<div class="quote-text">${quote.quote}</div>
30      <div class="attribution">- ${quote.person}</div><button class="delete-btn" data-id=${quote.id}>Delete Quote</button><button class="update-btn" data-id=${quote.id}>Change Quote</button>`;
31      quoteContainer.appendChild(newQuote);
32    });
33  } else {
34    quoteContainer.innerHTML = "<p>Your request returned no quotes.</p>";
35  }
36};
37
38//Bubbling event for deleting quote
39quoteContainer.addEventListener("click", (e) => {
40  if (e.target.classList.contains("delete-btn")) {
41    const id = e.target.dataset.id;
42    idTextField.value = id;
43    idTextField.disabled = true;
44    // alert(e.target.dataset.id)
45    fetch(`/api/quotes/${id}`, {
46      method: "DELETE",
47    })
48      .then((response) => {
49        if (response.ok) {
50          return response.json();
51        } else {
52          renderError(response);
53        }
54      })
55      .then((response) => {
56        renderQuotes(response.quotes);
57      });
58  }
59});
60
61//Bubbling event for updating quote
62quoteContainer.addEventListener("click", (e) => {
63  if (e.target.classList.contains("update-btn")) {
64    let quoteToUpdate;
65    const id = e.target.dataset.id;
66    idTextField.value = id
67    idTextField.disabled = true
68    console.log(id);
69    fetch(`/api/quotes/${id}`)
70      .then((response) => {
71        if (response.ok) {
72          return response.json();
73        } else {
74          renderError(response);
75        }
76      })
77      .then((response) => {
78        // console.log(response.quote)
79        quoteToUpdate = response.quote;
80        const quoteDiv = document.createElement('div')
81        quoteDiv.className = 'update-stuff'
82        const quote = document.createElement("textarea");
83        quote.className = 'dynamic-quote'
84        quote.rows = "5"
85        quote.columns = "6"
86        quote.value = quoteToUpdate.quote;
87        const person = document.createElement("input");
88        person.className = 'dynamic-person'
89        person.type = "text";
90        person.value = quoteToUpdate.person;
91        quoteDiv.append(quote)
92        quoteDiv.append(person)
93        if(updateContainer.length === 4){
94          updateContainer.removeChild(updateContainer.lastChild)
95          updateContainer.append(quoteDiv);
96        }
97        else{
98          updateContainer.append(quoteDiv)
99        }
100      });
101  }
102});
103
104updateById.addEventListener('click', () => {
105  const id = idTextField.value
106  const quote = document.querySelector('.dynamic-quote').value
107  const person = document.querySelector('.dynamic-person').value
108  
109  fetch(`/api/quotes/${id}?quote=${quote}&person=${person}`, {
110    method: "PUT"
111  })
112  .then(response => {
113    if(response.ok){
114      return response.json()
115    }else{
116      renderError(response)
117    }
118  })
119  .then(response => {
120    renderQuotes([response.quote])
121    updateContainer.removeChild(updateContainer.lastChild)
122  })
123})
124
125fetchAllButton.addEventListener("click", () => {
126  fetch("/api/quotes")
127    .then((response) => {
128      if (response.ok) {
129        return response.json();
130      } else {
131        renderError(response);
132      }
133    })
134    .then((response) => {
135      renderQuotes(response.quotes);
136      if(updateContainer.length > 3){
137        updateContainer.removeChild(updateContainer.lastChild)
138      }
139    });
140});
141
142fetchRandomButton.addEventListener("click", () => {
143  fetch("/api/quotes/random")
144    .then((response) => {
145      if (response.ok) {
146        return response.json();
147      } else {
148        renderError(response);
149      }
150    })
151    .then((response) => {
152      renderQuotes([response.quote]);
153    });
154});
155
156fetchByAuthorButton.addEventListener("click", () => {
157  const author = document.getElementById("author").value;
158  fetch(`/api/quotes?person=${author}`)
159    .then((response) => {
160      if (response.ok) {
161        return response.json();
162      } else {
163        renderError(response);
164      }
165    })
166    .then((response) => {
167      renderQuotes(response.quotes);
168    });
169});
170
Full Screen

wpml-media-posts-media-flag.js

Source: wpml-media-posts-media-flag.js Github

copy
1var WPML_Media_Posts_Media_Flag = WPML_Media_Posts_Media_Flag || {};
2
3jQuery(function ($) {
4
5    "use strict";
6
7	var updateContainer = $('#wpml-media-posts-media-flag');
8
9	var updateButton = updateContainer.find('.button-primary');
10	var spinner      = updateContainer.find('.spinner');
11
12	var prepareAction = updateContainer.data('prepareAction');
13	var prepareNonce  = updateContainer.data('prepareNonce');
14
15	var processAction = updateContainer.data('processAction');
16	var processNonce  = updateContainer.data('processNonce');
17
18	var statusContainer = updateContainer.find('.status');
19
20    function getQueryParams(qs) {
21        qs = qs.split('+').join(' ');
22
23        var params = {},
24            tokens,
25            re = /[?&]?([^=]+)=([^&]*)/g;
26
27        while (tokens = re.exec(qs)) {
28            params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
29        }
30
31        return params;
32    }
33
34
35    var queryParams = getQueryParams(location.search);
36    if (queryParams.run_setup) {
37        showProgress();
38        runSetup();
39    }
40
41    updateButton.on("click", function () {
42        showProgress();
43        runSetup();
44    });
45
46    function showProgress() {
47        spinner.css({visibility: "visible"});
48        updateButton.prop("disabled", true);
49    }
50
51    function hideProgress() {
52        spinner.css({visibility: "hidden"});
53        updateButton.prop("disabled", false);
54    }
55
56    function setStatus(statusText) {
57        statusContainer.html(statusText);
58    }
59
60    function runSetup() {
61        var data = {
62			action: prepareAction,
63			nonce: prepareNonce
64        };
65        $.ajax({
66            url: ajaxurl,
67            type: "POST",
68            dataType: "json",
69            data: data,
70            success: function (response) {
71				handleResponse(response);
72				if (!response.success) {
73					return;
74				}
75
76                if (response.data.status) {
77                    setStatus(response.data.status);
78                }
79                setInitialLanguage();
80			},
81			error: function (jqXHR, status, error) {
82				statusContainer.html(jqXHR.statusText || status || error);
83			}
84        });
85    }
86
87	function handleResponse(response) {
88		var error = [];
89
90		if (response.error) {
91			error.push(response.error);
92		}
93		if (!response.success && response.data) {
94			error.push(response.data);
95		}
96
97		if (error.length) {
98			statusContainer.html('<pre>' + error.join('</pre><pre>') + '</pre>');
99		}
100	}
101
102    function setInitialLanguage() {
103        var data = {
104			action: processAction,
105			nonce: processNonce
106        };
107        $.ajax({
108            url: ajaxurl,
109            type: "POST",
110            dataType: "json",
111            data: data,
112            success: function (response) {
113				handleResponse(response);
114				if (!response.success) {
115					return;
116				}
117
118				var message = response.message ? response.message : response.data.message;
119				setStatus(message);
120				setHasMediaFlag(0);
121			},
122			error: function (jqXHR, status, error) {
123				statusContainer.html(jqXHR.statusText || status || error);
124			}
125        });
126    }
127
128    function setHasMediaFlag(offset) {
129        var data = {
130			action: processAction,
131			nonce: processNonce,
132            offset: offset
133        };
134        $.ajax({
135            url: ajaxurl,
136            type: "POST",
137            dataType: "json",
138            data: data,
139            success: function (response) {
140				handleResponse(response);
141				if (!response.success) {
142					return;
143				}
144
145                if (response.data.status) {
146                    setStatus(response.data.status);
147                }
148                if (response.data.continue) {
149                    setHasMediaFlag(response.data.offset);
150                } else {
151                    if (queryParams.redirect_to) {
152                        location.href = queryParams.redirect_to;
153                    } else {
154                        location.reload();
155                    }
156                }
157			},
158			error: function (jqXHR, status, error) {
159				statusContainer.html(jqXHR.statusText || status || error);
160			}
161        });
162    }
163
164});
165
Full Screen

clusters_bundle_spec.js

Source: clusters_bundle_spec.js Github

copy
1import MockAdapter from 'axios-mock-adapter';
2import { loadHTMLFixture } from 'helpers/fixtures';
3import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
4import { setTestTimeout } from 'helpers/timeout';
5import Clusters from '~/clusters/clusters_bundle';
6import axios from '~/lib/utils/axios_utils';
7import initProjectSelectDropdown from '~/project_select';
8
9jest.mock('~/lib/utils/poll');
10jest.mock('~/project_select');
11
12useMockLocationHelper();
13
14describe('Clusters', () => {
15  setTestTimeout(1000);
16
17  let cluster;
18  let mock;
19
20  const mockGetClusterStatusRequest = () => {
21    const { statusPath } = document.querySelector('.js-edit-cluster-form').dataset;
22
23    mock = new MockAdapter(axios);
24
25    mock.onGet(statusPath).reply(200);
26  };
27
28  beforeEach(() => {
29    loadHTMLFixture('clusters/show_cluster.html');
30  });
31
32  beforeEach(() => {
33    mockGetClusterStatusRequest();
34  });
35
36  beforeEach(() => {
37    cluster = new Clusters();
38  });
39
40  afterEach(() => {
41    cluster.destroy();
42    mock.restore();
43  });
44
45  describe('class constructor', () => {
46    beforeEach(() => {
47      jest.spyOn(Clusters.prototype, 'initPolling');
48      cluster = new Clusters();
49    });
50
51    it('should call initPolling on construct', () => {
52      expect(cluster.initPolling).toHaveBeenCalled();
53    });
54
55    it('should call initProjectSelectDropdown on construct', () => {
56      expect(initProjectSelectDropdown).toHaveBeenCalled();
57    });
58  });
59
60  describe('updateContainer', () => {
61    describe('when creating cluster', () => {
62      it('should show the creating container', () => {
63        cluster.updateContainer(null, 'creating');
64
65        expect(cluster.creatingContainer.classList.contains('hidden')).toBeFalsy();
66        expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
67        expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
68        expect(window.location.reload).not.toHaveBeenCalled();
69      });
70
71      it('should continue to show `creating` banner with subsequent updates of the same status', () => {
72        cluster.updateContainer(null, 'creating');
73        cluster.updateContainer('creating', 'creating');
74
75        expect(cluster.creatingContainer.classList.contains('hidden')).toBeFalsy();
76        expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
77        expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
78        expect(window.location.reload).not.toHaveBeenCalled();
79      });
80    });
81
82    describe('when cluster is created', () => {
83      it('should hide the "creating" banner and refresh the page', () => {
84        jest.spyOn(cluster, 'setClusterNewlyCreated');
85        cluster.updateContainer(null, 'creating');
86        cluster.updateContainer('creating', 'created');
87
88        expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
89        expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
90        expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
91        expect(window.location.reload).toHaveBeenCalled();
92        expect(cluster.setClusterNewlyCreated).toHaveBeenCalledWith(true);
93      });
94
95      it('when the page is refreshed, it should show the "success" banner', () => {
96        jest.spyOn(cluster, 'setClusterNewlyCreated');
97        jest.spyOn(cluster, 'isClusterNewlyCreated').mockReturnValue(true);
98
99        cluster.updateContainer(null, 'created');
100        cluster.updateContainer('created', 'created');
101
102        expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
103        expect(cluster.successContainer.classList.contains('hidden')).toBeFalsy();
104        expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
105        expect(window.location.reload).not.toHaveBeenCalled();
106        expect(cluster.setClusterNewlyCreated).toHaveBeenCalledWith(false);
107      });
108
109      it('should not show a banner when status is already `created`', () => {
110        jest.spyOn(cluster, 'setClusterNewlyCreated');
111        jest.spyOn(cluster, 'isClusterNewlyCreated').mockReturnValue(false);
112
113        cluster.updateContainer(null, 'created');
114        cluster.updateContainer('created', 'created');
115
116        expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
117        expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
118        expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
119        expect(window.location.reload).not.toHaveBeenCalled();
120        expect(cluster.setClusterNewlyCreated).not.toHaveBeenCalled();
121      });
122    });
123
124    describe('when cluster has error', () => {
125      it('should show the error container', () => {
126        cluster.updateContainer(null, 'errored', 'this is an error');
127
128        expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
129
130        expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
131
132        expect(cluster.errorContainer.classList.contains('hidden')).toBeFalsy();
133
134        expect(cluster.errorReasonContainer.textContent).toContain('this is an error');
135      });
136
137      it('should show `error` banner when previously `creating`', () => {
138        cluster.updateContainer('creating', 'errored');
139
140        expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
141
142        expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
143
144        expect(cluster.errorContainer.classList.contains('hidden')).toBeFalsy();
145      });
146    });
147
148    describe('when cluster is unreachable', () => {
149      it('should show the unreachable warning container', () => {
150        cluster.updateContainer(null, 'unreachable');
151
152        expect(cluster.unreachableContainer.classList.contains('hidden')).toBe(false);
153      });
154    });
155
156    describe('when cluster has an authentication failure', () => {
157      it('should show the authentication failure warning container', () => {
158        cluster.updateContainer(null, 'authentication_failure');
159
160        expect(cluster.authenticationFailureContainer.classList.contains('hidden')).toBe(false);
161      });
162    });
163  });
164
165  describe('fetch cluster environments success', () => {
166    beforeEach(() => {
167      jest.spyOn(cluster.store, 'toggleFetchEnvironments').mockReturnThis();
168      jest.spyOn(cluster.store, 'updateEnvironments').mockReturnThis();
169
170      cluster.handleClusterEnvironmentsSuccess({ data: {} });
171    });
172
173    it('toggles the cluster environments loading icon', () => {
174      expect(cluster.store.toggleFetchEnvironments).toHaveBeenCalled();
175    });
176
177    it('updates the store when cluster environments is retrieved', () => {
178      expect(cluster.store.updateEnvironments).toHaveBeenCalled();
179    });
180  });
181
182  describe('handleClusterStatusSuccess', () => {
183    beforeEach(() => {
184      jest.spyOn(cluster.store, 'updateStateFromServer').mockReturnThis();
185      jest.spyOn(cluster, 'updateContainer').mockReturnThis();
186      cluster.handleClusterStatusSuccess({ data: {} });
187    });
188
189    it('updates clusters store', () => {
190      expect(cluster.store.updateStateFromServer).toHaveBeenCalled();
191    });
192
193    it('updates message containers', () => {
194      expect(cluster.updateContainer).toHaveBeenCalled();
195    });
196  });
197});
198
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)