How to use initWatch 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.

state.js

Source: state.js Github

copy
1import initWatch from "./initState/initWatch";
2import initData from "./initState/initData";
3import initComputed from "./initState/initComputed";
4
5// 初始化状态 注意这里的顺序 比如我经常面试会问到 是否能在data里面直接使用prop的值 为什么?
6// 这里初始化的顺序依次是 prop -> methods -> data ->computed -> watch
7export function initState(vm) {
8  // 获取传入的数据对象
9  const opts = vm.$options;
10  if (opts.props) {
11    // initProps(vm);
12  }
13  if (opts.methods) {
14    // initMethod(vm);
15  }
16  if (opts.data) {
17    // 初始化data
18    initData(vm);
19  }
20  if (opts.computed) {
21    initComputed(vm);
22  }
23  // 侦听属性
24  if (opts.watch) {
25    initWatch(vm);
26  }
27}
28
Full Screen

index.unit.http.test.js

Source: index.unit.http.test.js Github

copy
1const assert = require('assert')
2const sinon = require('sinon')
3const { oauth2init, oauth2callback, initWatch, onNewMessage } = require('..')
4const oauthLibrary = require('../lib/oauth')
5const gmailAPIClient = require('../lib/gmail-api-client')
6const slackClient = require('../lib/slack-client')
7let sandbox;
8
9function setupInitWatch(query) {
10  // mock dependencies
11  sandbox.stub(oauthLibrary, 'fetchToken')
12  sandbox.stub(gmailAPIClient, 'watchGmailInbox')
13
14  // Mock ExpressJS 'req' and 'res' parameters
15  const req = { query }
16  const res = {
17    send: sinon.stub(),
18    status: sinon.stub().returns({ send: sinon.stub() }),
19  }
20
21  return { req, res }
22}
23
24describe('test gmail-notifier functions', () => {
25  beforeEach(() => {
26    sandbox = sinon.createSandbox()
27  })
28
29  afterEach(() => {
30    sandbox.restore()
31  })
32
33  it('oauth2init: should redirect to Google connect id page', async () => {
34    // mock dependencies
35    sandbox.stub(oauthLibrary, 'getOAuth2Client').returns({
36      generateAuthUrl: function () {
37        return 'some-url'
38      },
39    })
40
41    // Mock ExpressJS 'req' and 'res' parameters
42    const req = {
43      query: {},
44      body: {},
45    }
46
47    const res = { redirect: sinon.stub() }
48
49    // Call tested function
50    await oauth2init(req, res)
51
52    // Verify behavior of tested function
53    assert.ok(res.redirect.calledOnce)
54    assert.deepStrictEqual(res.redirect.firstCall.args, ['some-url'])
55  })
56
57  it('oauth2callback: should redirect to initWatch', async () => {
58    // mock dependencies
59    sandbox.stub(oauthLibrary, 'saveToken')
60    sandbox.stub(oauthLibrary, 'getOAuth2Client').returns({
61      some: 'dummy client',
62    //eslint-disable-next-line no-unused-vars
63      getToken: function (code, callback) {
64        return { some: 'dummy token' }
65      },
66    //eslint-disable-next-line no-unused-vars
67      setCredentials: function (param) {},
68    })
69    sandbox
70      .stub(gmailAPIClient, 'getEmailAddress')
71      .returns('[email protected]')
72
73    // Mock ExpressJS 'req' and 'res' parameters
74    const req = {
75      query: { code: 'some-code' },
76      body: {},
77    }
78    const res = { redirect: sinon.stub() }
79
80    // Call tested function
81    await oauth2callback(req, res)
82
83    // Verify behavior of tested function
84    assert.ok(res.redirect.calledOnce)
85    assert.match(res.redirect.firstCall.args[0], /initWatch/)
86  })
87
88  it('initWatch: should init watch on gmail inbox', async () => {
89    const { req, res } = setupInitWatch({
90      emailAddress: '[email protected]',
91    })
92
93    // Call tested function
94    await initWatch(req, res)
95
96    // Verify behavior of tested function
97    assert.ok(res.send.calledOnce)
98    assert.match(res.send.firstCall.args[0], /Watch initialized/)
99    assert.match(res.send.firstCall.args[0], /[email protected]/)
100  })
101
102  it('initWatch: should return error 400 if no email address is specified', async () => {
103    const { req, res } = setupInitWatch({
104      NoemailAddress: '[email protected]',
105    })
106
107    // Call tested function
108    await initWatch(req, res)
109
110    // Verify behavior of tested function
111    assert.ok(res.status.calledOnce)
112    assert.ok(res.status().send.calledOnce)
113    assert.equal(res.status.firstCall.args[0], 400)
114    assert.match(
115      res.status().send.firstCall.args[0],
116      /No emailAddress specified./
117    )
118  })
119
120  it('initWatch: should return error 400 if a bad address is specified', async () => {
121    const { req, res } = setupInitWatch({
122      emailAddress: 'some-emailaddress.com',
123    })
124
125    // Call tested function
126    await initWatch(req, res)
127
128    // Verify behavior of tested function
129    assert.ok(res.status.calledOnce)
130    assert.ok(res.status().send.calledOnce)
131    assert.equal(res.status.firstCall.args[0], 400)
132    assert.match(res.status().send.firstCall.args[0], /Invalid emailAddress/)
133  })
134
135  it('onNewMessage: should received message from Pub/sub and retreive email content', async () => {
136    // given
137    sandbox.stub(oauthLibrary, 'fetchToken').returns(Promise.resolve())
138    sandbox.stub(oauthLibrary, 'getEntities').returns(Promise.resolve())
139    sandbox.stub(oauthLibrary, 'saveEntity').returns(Promise.resolve())
140    sandbox
141      .stub(gmailAPIClient, 'listMessages')
142      .returns(Promise.resolve( [{ id: '1234' }]))
143    const gmailMessage = require('./gmail-message-response.json')
144    sandbox
145      .stub(gmailAPIClient, 'getMessageById')
146      .returns({ data: gmailMessage })
147    const slackClientSpy = sandbox.stub(slackClient, 'postMessageToSlack').returns(Promise.resolve())
148
149    const message = {
150      // from https://developers.google.com/gmail/api/guides/push#watch_response
151      // This is the actual notification data, as base64url-encoded JSON.
152      data: 'eyJlbWFpbEFkZHJlc3MiOiAidXNlckBleGFtcGxlLmNvbSIsICJoaXN0b3J5SWQiOiAiMTIzNDU2Nzg5MCJ9',
153      // This is a Cloud Pub/Sub message id, unrelated to Gmail messages.
154      messageId: '2070443601311540',
155      // This is the publish time of the message.
156      publishTime: '2021-02-26T19:13:55.749Z',
157    }
158
159    // when
160    const result = await onNewMessage(message)
161
162    // then
163    assert.equal(result.length, 1)
164    assert.match(await result[0].sentMessage, /CORPS DU MAIL/)
165    sandbox.assert.called(slackClientSpy);
166  })
167})
168
Full Screen

drtv-contact-trust.js

Source: drtv-contact-trust.js Github

copy
1'use strict';
2
3angular.module('cmContacts').directive('cmContactTrust',[
4    'cmContactsModel',
5    function (cmContactsModel){
6        return {
7            restrict: 'E',
8            templateUrl: 'comps/contacts/drtv-contact-trust.html',
9            controller: function($scope, $element, $attrs){
10
11                $scope.withText = ('cmWithText' in $attrs) ? true : false;
12
13                var contact,
14                    watchOn = true;
15
16                function init(){
17                    $scope.$on('$destroy',function(){
18                        if(contact && 'securityAspects' in contact)
19                            contact.securityAspects.off('refresh', refresh);
20                    });
21
22                    initWatch();
23                }
24
25                function initWatch(data){
26                    if(!watchOn || !data)
27                        return false;
28
29                    contact = data.contactType
30                    ? data
31                    : cmContactsModel.findByIdentity(data);
32
33                    if(contact)
34                        watchOn = false;
35                    else
36                        return false;
37
38                    contact.securityAspects.on('refresh', refresh);
39
40                    refresh();
41                }
42
43                function refresh(){
44                    contact.securityAspects
45                        .get()
46                        .then(function(){
47                            $scope.noKey = contact.securityAspects.applies('NO_KEY');
48                            $scope.hasKey = contact.securityAspects.applies('AT_LEAST_ONE_KEY');
49                            $scope.hasAuthenticatedKey = contact.securityAspects.applies('AT_LEAST_ONE_AUTHENTICATED_KEY');
50                        });
51                }
52
53                init();
54
55                $scope.$watchCollection($attrs.cmData, initWatch);
56            }
57        }
58    }
59]);
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)