Best JavaScript code snippet using playwright-internal
NotificationsProvider.js
Source:NotificationsProvider.js
1/**2 * NotificationsProvider.js3 *4 * Author: Caleb Panza5 * Created: Apr 02, 20216 *7 * note : This file was copied from the file: Provider.js in @apollosproject/ui-notification. There was an issue with the `navigate` method. I've left the Core Apollos code in as a comment just for reference along with a description of the change8 *9 * todo : We should track the issue and move this file back to the Core code once a change/fix10 * has been approved and implemented.11 *12 * note : August 21, 2020 : In preparation for the eventual arrival of a Notification Center, we also have some temporary code inside of13 */14import React, { Component } from 'react';15import { Linking, Platform } from 'react-native';16import PropTypes from 'prop-types';17import gql from 'graphql-tag';18import { withApollo } from '@apollo/client/react/hoc';19import { get } from 'lodash';20import OneSignal from 'react-native-onesignal';21import {22 resolvers,23 defaults,24} from '@apollosproject/ui-notifications/src/store';25import PushProvider from '@apollosproject/ui-notifications/src/pushProvider';26import { useLinkRouter } from 'hooks';27const UPDATE_DEVICE_PUSH_ID = gql`28 mutation updateDevicePushId($pushId: String!) {29 updateDevicePushId(pushId: $pushId) @client30 }31`;32const GET_PUSH_ID = gql`33 query {34 pushId @client35 }36`;37class NotificationsInit extends Component {38 static propTypes = {39 children: PropTypes.oneOfType([40 PropTypes.arrayOf(PropTypes.node),41 PropTypes.node,42 ]).isRequired,43 oneSignalKey: PropTypes.string.isRequired,44 navigate: PropTypes.func.isRequired,45 client: PropTypes.shape({46 mutate: PropTypes.func,47 addResolvers: PropTypes.func,48 writeQuery: PropTypes.func,49 onClearStore: PropTypes.func,50 }).isRequired,51 };52 static navigationOptions = {};53 constructor(props) {54 super(props);55 const { client } = props;56 client.addResolvers(resolvers);57 client.writeQuery({ query: GET_PUSH_ID, data: defaults });58 client.onClearStore(() =>59 client.writeQuery({ query: GET_PUSH_ID, data: defaults })60 );61 }62 async componentDidMount() {63 OneSignal.setAppId(this.props.oneSignalKey);64 OneSignal.setNotificationWillShowInForegroundHandler(this.onReceived);65 OneSignal.setNotificationOpenedHandler(this.onOpened);66 const deviceState = await OneSignal.getDeviceState();67 this.onIds(deviceState);68 Linking.getInitialURL().then((url) => {69 this.navigate(url);70 });71 Linking.addEventListener('url', ({ url }) => this.navigate(url));72 }73 componentWillUnmount() {74 Linking.removeEventListener('url');75 OneSignal.clearHandlers();76 }77 navigate = (rawUrl) => {78 if (!rawUrl) return;79 this.props.routeLink(rawUrl);80 };81 onReceived = async (notification) => {82 console.log('Notification received: ', notification);83 };84 onOpened = (openResult) => {85 console.log('Message: ', openResult.notification.body);86 console.log('Data: ', openResult.notification.additionalData);87 console.log('openResult: ', openResult);88 // URL looks like this89 // apolloschurchapp://AppStackNavigator/Connect90 // apolloschurchapp://SomethingElse/Connect91 // apolloschurchapp://SomethingElse/ContentSingle?itemId=SomeItemId:blablalba92 const url = Platform.select({93 ios: get(openResult, 'notification.additionalData.url'),94 android: get(openResult, 'notification.launchURL'),95 });96 if (url) {97 this.navigate(url);98 }99 };100 onIds = (device) => {101 this.props.client.mutate({102 mutation: UPDATE_DEVICE_PUSH_ID,103 variables: { pushId: device.userId },104 });105 };106 render() {107 return <PushProvider>{this.props.children}</PushProvider>;108 }109}110const NotificationsInitWithApollo = withApollo(NotificationsInit);111const NotificationsInitHookProvider = (props) => {112 const { routeLink } = useLinkRouter();113 return <NotificationsInitWithApollo {...props} routeLink={routeLink} />;114};...
pushContext.jsx
Source:pushContext.jsx
1import {2 createContext,3 useContext,4 useEffect,5 useMemo,6 useRef,7 useState,8} from 'react';9import propTypes from 'prop-types';10import { useKolibriStateContext } from './kolibriContext';11import { isDesktop, mutateBigNumber } from '../utils';12// state context13const PushStateContext = createContext({});14PushStateContext.displayName = 'PushStateContext';15const usePushStateContext = () => {16 const context = useContext(PushStateContext);17 if (!context) {18 throw new Error('PushStateContext must be used within a PushProvider');19 }20 return context;21};22// dispatch context23const PushDispatchContext = createContext({});24PushDispatchContext.displayName = 'PushDispatchContext';25const usePushDispatchContext = () => {26 const context = useContext(PushDispatchContext);27 if (!context) {28 throw new Error('PushDispatchContext must be used within a PushProvider');29 }30 return context;31};32// Provider33const PushProvider = ({ children }) => {34 const { tezosPrice } = useKolibriStateContext();35 const [permission, setPermission] = useState(false);36 const [notifyOracle, setNotifyOracle] = useState(false);37 const firstUpdate = useRef(true);38 const desktop = isDesktop();39 const requestPermission = () => {40 if (desktop) {41 return Notification.requestPermission();42 }43 return () => null;44 };45 let handleSetNotify;46 try {47 const storage = localStorage;48 handleSetNotify = () => {49 if (permission) {50 setNotifyOracle(!notifyOracle);51 storage.setItem('oracleNotify', !notifyOracle);52 } else {53 requestPermission();54 }55 };56 useEffect(() => {57 const storageOracleNotify = JSON.parse(storage.getItem('oracleNotify'));58 return storageOracleNotify59 ? setNotifyOracle(storageOracleNotify)60 : storage.setItem('oracleNotify', false);61 }, []);62 } catch {63 handleSetNotify = () => {64 if (permission) {65 setNotifyOracle(!notifyOracle);66 } else {67 requestPermission();68 }69 };70 }71 useEffect(() => {72 if (tezosPrice) {73 if (firstUpdate.current) {74 firstUpdate.current = false;75 return;76 }77 if (notifyOracle) {78 // eslint-disable-next-line no-new79 new Notification('Hey! Kolibri Oracle has updated!', {80 body: `New XTZ/USD price is ${mutateBigNumber(tezosPrice.price)}$`,81 });82 }83 }84 }, [tezosPrice]);85 useEffect(() => {86 if (desktop) {87 setPermission(Notification.permission === 'granted');88 }89 }, []);90 const stateValue = useMemo(91 () => ({ permission, notifyOracle }),92 [permission, notifyOracle],93 );94 const dispatchValue = useMemo(95 () => ({ requestPermission, handleSetNotify }),96 [requestPermission, handleSetNotify],97 );98 return (99 <PushStateContext.Provider value={stateValue}>100 <PushDispatchContext.Provider value={dispatchValue}>101 {children}102 </PushDispatchContext.Provider>103 </PushStateContext.Provider>104 );105};106export { usePushStateContext, usePushDispatchContext, PushProvider };107PushProvider.propTypes = {108 children: propTypes.node.isRequired,...
push-send-helper.test.js
Source:push-send-helper.test.js
1require('./test-env');2const { createEndpointStub, publishStub } = mocks.awsStub.getStubs();3const pushProvider = require('../src/helpers/push-send');4const pushRegister = require('../src/services/recipient-profile/routes/push-register');5const locationGroup = 'location1';6const multiDB = require('mongoose-multi-connect');7const Notification = multiDB.getModel('notifications', locationGroup);8const RecipientProfile = multiDB.getModel('recipientprofiles', locationGroup);9const platform = 'android';10const app = { name: 'android' };11const token = String(new Date());12const message = String(new Date());13const error = { message: String(new Date()) };14const payload = { badge: 5 };15const EndpointArn = '1';16describe('Push', () => {17 before(() => ctx.pushSendSpy = sinon.spy(pushProvider, 'send'));18 after(() => ctx.pushSendSpy.restore());19 describe('send', () => {20 describe('success', () => {21 before(() => {22 createEndpointStub.returns({ EndpointArn: '1' });23 publishStub.returns({ MessageId: '2' });24 });25 it('should be sent', () => {26 return pushProvider27 .send({ platform, token, message, payload, app, locationGroup })28 .then(async res => {29 assert.equal(res.platform, platform);30 assert.equal(res.app, app);31 assert.equal(res.message, message);32 assert.equal(res.token, token);33 assert.deepEqual(res.payload, payload);34 assert.ok(res.platformApplicationArn);35 assert.ok(res.providerMessageId);36 assert.ok(res.sendDate);37 assert.ok(ctx.pushSendSpy.called);38 assert.ok(await Notification.findOne({ providerMessageId: res.providerMessageId }));39 });40 });41 });42 describe('fail', () => {43 before(() => {44 createEndpointStub.returns({ EndpointArn });45 publishStub.throws(error);46 });47 before(() => {48 pushProvider.send({ platform, token, message, payload, app, locationGroup });49 });50 it('should be fail', async () => {51 await helpers.timeout(500);52 const res = await Notification.findOne({ error });53 assert.ok(res);54 });55 });56 });57 describe('old token', () => {58 const oldTokenError = { message: 'Invalid parameter: This endpoint is already registered with a different token.' };59 const oldToken = String(new Date());60 before(async () => {61 await pushRegister({ token: oldToken, deviceId: 'some', recipientId: 'some', app }, { locationGroup });62 });63 before(async () => {64 const res = await RecipientProfile.findOne({ token: oldToken });65 assert.ok(res);66 });67 before(() => {68 createEndpointStub.returns({ EndpointArn });69 publishStub.throws(oldTokenError);70 });71 before(() => {72 pushProvider.send({ platform, token: oldToken, message, payload, app, locationGroup });73 });74 it('should be no old device token', async () => {75 await helpers.timeout(500);76 const res = await RecipientProfile.findOne({ token: oldToken });77 assert.ok(!res);78 });79 });...
mutations.js
Source:mutations.js
1// ä¿®æ¹stateå¼ å åæ¥äºä»¶æ¹æ³2const mutations = {3 // ç¨æ·åºæ¬ä¿¡æ¯4 setUserBaseInfo(state, {5 nickName,6 avatarUrl7 }) {8 state.nickName = nickName;9 state.avatarUrl = avatarUrl;10 this.commit('setStorage', {11 str: 'nickName',12 val: nickName13 })14 this.commit('setStorage', {15 str: 'avatarUrl',16 val: avatarUrl17 })18 },19 // ç¨æ· encryptedDataãivãsignature20 setUserOtherInfo(state, {21 encryptedData,22 iv,23 signature24 }) {25 state.encryptedData = encryptedData;26 state.iv = iv;27 state.signature = signature;28 this.commit('setStorage', {29 str: "encryptedData",30 val: encryptedData31 });32 this.commit('setStorage', {33 str: "iv",34 val: iv35 });36 this.commit('setStorage', {37 str: "signature",38 val: signature39 })40 },41 // ç»å½ tokenãexpired42 setToken(state, {43 token,44 expired45 }) {46 state.token = token;47 state.token = expired;48 this.commit('setStorage', {49 str: "token",50 val: token51 });52 this.commit('setStorage', {53 str: "expired",54 val: expired55 });56 },57 // ä¾åºå58 setProvider(state, {59 service,60 provider61 }) {62 let str = service + 'Provider';63 state[str] = provider;64 this.commit('setStorage', {65 str: str,66 val: provider67 })68 },69 // ç¼åä¿¡æ¯70 setStorage(state, {71 str,72 val73 }) {74 if (process.env.NODE_ENV === 'development') {75 str = 'dev' + str;76 } else {77 str = 'prd' + str;78 }79 try {80 uni.setStorageSync(str, val)81 } catch (e) {82 console.log(str, 'ç¼å设置失败')83 }84 },85 // è·å设å¤ä¿¡æ¯86 getSystemInfo(state) {87 uni.getSystemInfo({88 success(res) {89 state.systemInfo = res;90 }91 });92 },93 //åå§å storeä»åº94 initStore(state) {95 let str = '';96 if (process.env.NODE_ENV === 'development') {97 str = 'dev'98 } else {99 str = 'prd'100 }101 state.oauthProvider = uni.getStorageSync(str + 'oauthProvider');102 state.oauthCode = uni.getStorageSync(str + 'oauthCode');103 state.shareProvider = uni.getStorageSync(str + 'shareProvider');104 state.payProvider = uni.getStorageSync(str + 'payProvider');105 state.pushProvider = uni.getStorageSync(str + 'pushProvider');106 state.token = uni.getStorageSync(str + 'token');107 state.nickName = uni.getStorageSync(str + 'nickName');108 state.avatarUrl = uni.getStorageSync(str + 'avatarUrl');109 state.encryptedData = uni.getStorageSync(str + 'encryptedData');110 state.iv = uni.getStorageSync(str + 'iv');111 state.signature = uni.getStorageSync(str + 'signature');112 state.expired = uni.getStorageSync(str + 'expired');113 this.commit('getSystemInfo')114 },115 isGetUserInfo(state, {116 val117 }) {118 state.hasUserInfo = val;119 },120}...
Provider.js
Source:Provider.js
1import Vue from 'vue'2const state = {3 providers: []4}5const getters = {6 getProviders (state) {7 return state.providers8 },9 getProviderById: state => id => {10 return state.providers.find(p => p.module_id === id)11 }12}13const mutations = {14 pushProvider (state, provider) {15 if (provider) {16 let idx = state.providers.findIndex(e => e.ID === provider.ID)17 if (idx === -1) {18 state.providers.push(provider)19 } else {20 state.providers.slice(idx, 1, provider)21 }22 }23 },24 sliceProvider (state, id) {25 if (id) {26 let idx = state.providers.findIndex(e => e.module_id === id)27 if (idx !== -1) {28 state.providers.slice(idx, 1)29 }30 }31 }32}33const actions = {34 create ({ commit, state }, payload) {35 return new Promise((resolve, reject) => {36 if (!payload.data || !payload.module_id || !payload.profile_id) {37 reject(new Error('Malformed object'))38 } else {39 Vue.api.post('provider', payload).then((res) => {40 commit('pushProvider', res.data)41 resolve(res.data)42 }).catch(reject)43 }44 })45 },46 read ({ commit, state }, id) {47 return new Promise((resolve, reject) => {48 if (!id) {49 reject(new Error('Read needs an id'))50 } else {51 Vue.api.get(`provider/${id}`).then((res) => {52 commit('pushProvider', res.data)53 resolve(res.data)54 }).catch(reject)55 }56 })57 },58 update ({ commit, state }, payload) {59 return new Promise((resolve, reject) => {60 if (!payload.id || !payload.data) {61 reject(new Error('Update needs an id and data'))62 } else {63 Vue.api.get(`provider/${payload.id}`, payload.data).then((res) => {64 commit('pushProvider', res.data)65 resolve(res.data)66 }).catch(reject)67 }68 })69 },70 delete ({ commit, state }, id) {71 return new Promise((resolve, reject) => {72 if (!id) {73 reject(new Error('Delete needs an id'))74 } else {75 Vue.api.delete(`provider/${id}`).then(() => {76 commit('sliceProvider', id)77 resolve()78 }).catch(reject)79 }80 })81 },82 readAll ({ commit, state }) {83 return new Promise((resolve, reject) => {84 Vue.api.get(`providers`).then((res) => {85 for (let provider of res.data) {86 commit('pushProvider', provider)87 }88 resolve(res.data)89 }).catch(reject)90 })91 }92}93export default {94 state,95 getters,96 mutations,97 actions...
ReactFiberNewContext.js
Source:ReactFiberNewContext.js
...10import type {ReactContext} from 'shared/ReactTypes';11import type {StackCursor, Stack} from './ReactFiberStack';12import warning from 'fbjs/lib/warning';13export type NewContext = {14 pushProvider(providerFiber: Fiber): void,15 popProvider(providerFiber: Fiber): void,16};17export default function(stack: Stack) {18 const {createCursor, push, pop} = stack;19 const providerCursor: StackCursor<Fiber | null> = createCursor(null);20 const valueCursor: StackCursor<mixed> = createCursor(null);21 const changedBitsCursor: StackCursor<number> = createCursor(0);22 let rendererSigil;23 if (__DEV__) {24 // Use this to detect multiple renderers using the same context25 rendererSigil = {};26 }27 function pushProvider(providerFiber: Fiber): void {28 const context: ReactContext<any> = providerFiber.type._context;29 push(changedBitsCursor, context._changedBits, providerFiber);30 push(valueCursor, context._currentValue, providerFiber);31 push(providerCursor, providerFiber, providerFiber);32 context._currentValue = providerFiber.pendingProps.value;33 context._changedBits = providerFiber.stateNode;34 if (__DEV__) {35 warning(36 context._currentRenderer === null ||37 context._currentRenderer === rendererSigil,38 'Detected multiple renderers concurrently rendering the ' +39 'same context provider. This is currently unsupported.',40 );41 context._currentRenderer = rendererSigil;...
AppContextProvider.jsx
Source:AppContextProvider.jsx
1import propTypes from 'prop-types';2import { ErrorProvider } from './errorContext';3import { I18nProvider } from './i18nContext';4import { ThemeProvider } from './themeContext';5import { BeaconProvider } from './beaconContext';6import { KolibriProvider } from './kolibriContext';7import { PushProvider } from './pushContext';8import { ModalProvider } from './modalContext';9const AppContextProvider = ({ children }) => {10 return (11 <ModalProvider>12 <ErrorProvider>13 <ThemeProvider>14 <I18nProvider>15 <BeaconProvider>16 <KolibriProvider>17 <PushProvider>{children}</PushProvider>18 </KolibriProvider>19 </BeaconProvider>20 </I18nProvider>21 </ThemeProvider>22 </ErrorProvider>23 </ModalProvider>24 );25};26export default AppContextProvider;27AppContextProvider.propTypes = {28 children: propTypes.node.isRequired,...
PushProvider.js
Source:PushProvider.js
1'use strict';2const { ServiceProvider } = require('@adonisjs/fold');3const Client = require('../src/client');4class PushProvider extends ServiceProvider {5 register() {6 this.app.singleton('Adonis/Notify/Push', () => {7 const Config = this.app.use('Adonis/Src/Config');8 const _Client = new Client(Config.get('notification'));9 const Push = require('../src/Push/index');10 return new Push(Config.get('notification'), _Client);11 });12 }13}...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.evaluate(() => {7 return {8 headers: {9 },10 };11 });12 });13 await page.waitForTimeout(5000);14 await browser.close();15})();16pushProvider(url: string, provider: ProviderFunction): void17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch({ headless: false });20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.evaluate(() => {23 return {24 headers: {25 },26 };27 });28 });29 await page.waitForTimeout(5000);30 await browser.close();31})();32popProvider(url: string): void
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.pushProvider({
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const device = playwright.devices['iPhone 6'];7 await page.emulate(device);8 await page.screenshot({ path: 'google.png' });9 await browser.close();10})();11const playwright = require('playwright');12(async () => {13 const browser = await playwright.chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 const device = playwright.devices['iPhone 6'];17 await page.emulate(device);18 await page.screenshot({ path: 'google.png' });19 await browser.close();20})();21const playwright = require('playwright');22(async () => {23 const browser = await playwright.chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 const device = playwright.devices['iPhone 6'];27 await page.emulate(device);28 await page.screenshot({ path: 'google.png' });29 await browser.close();30})();31const playwright = require('playwright');32(async () => {33 const browser = await playwright.chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 const device = playwright.devices['iPhone 6'];37 await page.emulate(device);38 await page.screenshot({ path: 'google.png' });39 await browser.close();40})();41const playwright = require('playwright');42(async () => {43 const browser = await playwright.chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 console.log(pushSubscription.endpoint);7 await browser.close();8})();9BrowserContext.pushProvider() method
Using AI Code Generation
1const { chromium } = require('playwright');2const { pushProvider } = require('playwright/internal');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { createPushProvider } = require('playwright-core/lib/server/push');3const { createServer } = require('http');4const { createReadStream } = require('fs');5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 const pushProvider = createPushProvider();10 const server = createServer((req, res) => {11 if (req.url === '/push') {12 pushProvider.pushToAll();13 res.end('Push sent');14 } else {15 res.end('Hello World');16 }17 });18 server.listen(3000);19 await page.evaluate(() => {20 navigator.serviceWorker.register('/sw.js');21 });22 await new Promise((resolve) => setTimeout(resolve,
Using AI Code Generation
1const { chromium } = require('playwright');2const { getTestState } = require('@playwright/test');3const { pushProvider } = require('playwright/lib/server/webkit/wkBrowser');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const webKitBrowser = getTestState(page).browser;9 const webkit = await pushProvider(webKitBrowser);10 await page.click('button');11 await page.waitForEvent('popup');12})();13const test = require('@playwright/test');14test.describe('test', () => {15 test('test', async ({ page }) => {16 await page.click('button');17 await page.waitForEvent('popup');18 });19});
Using AI Code Generation
1const { chromium } = require('playwright-chromium');2const { devices } = require('playwright');3const iPhone11 = devices['iPhone 11 Pro'];4const path = require('path');5const fs = require('fs');6const webpush = require('web-push');7(async () => {8 const browser = await chromium.launch();9 const context = await browser.newContext({10 });11 const page = await context.newPage();12 await page.click('text="Enable Push Messaging"');13 await page.click('text="Send me a Notification"');14 await page.evaluate(async () => {15 const pushProvider = window.__playwright__internal__browserContext__._browser._pushProviders[0];16 await pushProvider.push(pushSubscription, 'Hello World!');17 });18 await browser.close();19})();20const { chromium } = require('playwright-chromium');21const { devices } = require('playwright');22const iPhone11 = devices['iPhone 11 Pro'];23const path = require('path');24const fs = require('fs');25const webpush = require('web-push');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext({29 });30 const page = await context.newPage();31 await page.click('text="Enable Push Messaging"');32 await page.click('text="Send me a Notification"');33 await page.evaluate(async () => {34 const pushProvider = window.__playwright__internal__browserContext__._browser._pushProviders[0];35 await pushProvider.push(pushSubscription, 'Hello World!');36 });37 await browser.close();38})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!