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

inject-recorder.js

Source: inject-recorder.js Github

copy
1// This file is loaded by the recorder app.
2
3// TODO-barret-verify; Is it `opt` or `cmd` for mac?
4// TODO-future-test-with-shinyjster:
5// * capture input
6// * capture output
7// * capture all values (via button)
8// * capture all values (via keyboard)
9// * capture screenshot (via button)
10// * capture screenshot (via keyboard)
11// * file download
12// * update input value via `updateSliderValue()`?
13// * click on input button
14
15
16window.recorder = (function() {
17    var recorder = {
18        token: randomId(),
19        testEvents: []
20    };
21
22
23    // Code injection
24    $(document).ready(function() {
25
26        var status = {
27            frameReady: false,
28            recorderCodeReady: false,
29            codeHasBeenInjected: false
30        };
31
32        function evalCodeInFrame(code) {
33            var message = {
34                token: "abcdef",
35                code: code
36            };
37            $('#app-iframe')[0].contentWindow.postMessage(message, "*");
38        }
39
40
41        // Check that the frame is ready with its Shiny app
42        var frameReadyChecker = window.setInterval(function() {
43            if (status.frameReady) {
44                injectRecorderJS();
45                clearTimeout(frameReadyChecker);
46                return;
47            }
48
49
50            // Find out when iframe app is ready - this tells it to send back
51            // a message indicating that it's ready.
52            evalCodeInFrame(
53                // "if (Shiny && Shiny.shinyapp && Shiny.shinyapp.config) {" +
54                "if (window.$) {" +
55                    "var message = {" +
56                        "token: '" + recorder.token + "', " +
57                        "type: 'frameReady'" +
58                    "};\n" +
59                    "parent.postMessage(message, '*');" +
60                "}"
61            );
62        }, 100);
63
64        var recorderJS;
65        Shiny.addCustomMessageHandler("recorder_js", function(message) {
66            status.recorderCodeReady = true;
67            recorderJS = message;
68            injectRecorderJS();
69        });
70
71        // Inject recorder code into iframe, but only if hasn't already been done.
72        function injectRecorderJS() {
73            if (!status.codeHasBeenInjected &&
74                status.frameReady &&
75                status.recorderCodeReady)
76            {
77                evalCodeInFrame(recorderJS);
78                evalCodeInFrame("window.shinyRecorder.token = '" + recorder.token + "';");
79                evalCodeInFrame("window.shinyRecorder.sendWindowSize();");
80                status.codeHasBeenInjected = true;
81            }
82        }
83
84
85        function triggerTestEvent(obj) {
86            if (!obj.token) obj.token = recorder.token;
87            obj.time = Date.now();
88            recorder.testEvents.push(obj);
89            // Send updated values to server
90            Shiny.onInputChange("testevents:shinytest2.testevents", recorder.testEvents);
91        }
92
93
94        // Set up message receiver. Code is evaluated with `status` as the
95        // context, so that the value can be modified in the right place.
96        window.addEventListener("message", function(e) {
97            var message = e.data;
98            if (message.token !== recorder.token)
99                return;
100
101            function addTestEvent() {
102                triggerTestEvent(message);
103            }
104
105            switch (message.type) {
106                case 'frameReady':
107                    status.frameReady = true;
108                    message.type = "initialize";
109                    addTestEvent();
110                    break;
111                case 'inputEvent':
112                    // Filter out clientdata items
113                    if (message.name.indexOf(".clientdata") === 0)
114                        return;
115                case 'outputEvent':
116                case 'expectValues':
117                case 'expectScreenshot':
118                case 'expectDownload':
119                case 'setWindowSize':
120                case 'waitForIdle':
121                    addTestEvent();
122                    break;
123                default:
124                    console.error("Unknown message type:", message);
125            }
126
127            // console.log("message code: ", message.code);
128            // (function() { eval(message.code); }).call(status);
129        });
130
131        // Generate snapshot via keypress within parent context as well
132        $(document).keydown(function(e) {
133            if (!(e.ctrlKey || e.metaKey)) return;
134            if (!e.shiftKey) return;
135            // Trigger a snapshot on Ctrl-shift-S or Cmd-shift-S (Mac)
136            if (e.which === 83) triggerTestEvent({type: "expectScreenshot"});
137            // Trigger a snapshot on Ctrl-shift-V or Cmd-shift-V (Mac)
138            if (e.which === 86) triggerTestEvent({type: "expectValues"});
139            // Trigger a snapshot on Ctrl-shift-I or Cmd-shift-I (Mac)
140            if (e.which === 73) triggerTestEvent({type: "waitForIdle"});
141        });
142
143        $(document).on("shiny:inputchanged", function(event) {
144            if (event.name === "values") triggerTestEvent({type: "expectValues"});
145            if (event.name === "screenshot") triggerTestEvent({type: "expectScreenshot"});
146        });
147
148        // Enable save button when there is an expectation
149        Shiny.addCustomMessageHandler("enable_save_button", function(message) {
150            $("#exit_save").toggleClass("disabled", !message);
151        });
152
153    });
154
155
156    // ------------------------------------------------------------------------
157    // Utility functions
158    // ------------------------------------------------------------------------
159
160    function randomId() {
161        return Math.floor(0x100000000 + (Math.random() * 0xF00000000)).toString(16);
162    }
163
164    return recorder;
165})();
166
Full Screen

utils.js

Source: utils.js Github

copy
1var utils = {
2    /**
3     * 触发点击事件
4     * @param  {Element} elem dom元素
5     */
6    click:function(elem){
7        var ev = document.createEvent("MouseEvent");
8        ev.initMouseEvent(
9            "click",
10            true /* bubble */, true /* cancelable */,
11            window, null,
12            0, 0, 0, 0, /* coordinates */
13            false, false, false, false, /* modifier keys */
14            0 /*left*/, null
15        );
16        elem.dispatchEvent(ev);
17    },
18    /**
19     * 与截图对比差异
20     * @param  {[type]}   name  对比图名字
21     * @param  {Function} done
22     * @param  {Object} tolerantCfg 容错配置
23     * @param  {Number} tolerantCfg.value 允许颜色最大的差值 默认为5
24     * @param  {Number} tolerantCfg.num 允许错误像素点数量 默认为10
25     * */
26    diffWithScreenshot:function(name, done, tolerantCfg){
27        var that = this;
28        that.takeScreenshot(name, function(screenshotImg){
29            if(screenshotImg){
30                utils.loadImage('../expectScreenshot/' + name + '.png', function(specImg){
31                    if(specImg){
32                        var diff = utils.diffImage(screenshotImg, specImg);
33                        if(diff < 10){
34                            done();
35                        }
36                        else{
37                            done(new Error('diff image error:' + name + ', diff:' + diff));
38                        }
39                    }
40                    else{
41                        console.log('no spec image:' + name);
42                        done();
43                    }
44                });
45            }
46            else{
47                setTimeout(function(){
48                    done();
49                }, 100);
50            }
51        });
52    },
53
54    /**
55     * 用例结束后截屏
56     */
57    screenshot:function(callback, context) {
58      var name = new Date().getTime();
59      this.takeScreenshot(name, callback, context);
60    },
61
62    /**
63     * 截屏
64     * @param  {String} name 图片名
65     * @param  {Function} callback 回调
66     */
67    takeScreenshot:function(name, callback, context) {
68        var that = this;
69        setTimeout(function(){
70            _macaca_uitest.screenshot(name + '.png', function() {
71              if (callback) {
72                if (context) {
73                _macaca_uitest.appendToContext(context, '../reports/screenshots/' + name + '.png');
74                }
75                that.loadImage('../reports/screenshots/' + name + '.png', callback, context);
76              }
77            });
78        }, window._IS_TRAVIS?1000:100);
79    },
80    /**
81     * 加载图片
82     * @param  {String} src 图片地址
83     * @param  {Function} callback 加载回调,成功会传image参数,失败传null
84     */
85    loadImage:function(src, callback, context){
86        var img = new Image();
87        img.onerror = function(){
88            callback && callback(null);
89        };
90        img.onload = function(){
91          if (context) {
92            callback && callback();
93          } else {
94            callback && callback(img);
95          }
96        };
97        img.src = src;
98    },
99    /**
100     * 对比图像是否相同
101     * @param  {Image|String} img0
102     * @param  {Image|String} img1
103     * @param  {Object} tolerantCfg 容错配置
104     * @param  {Number} tolerantCfg.value 允许颜色最大的差值 默认为5
105     * @param  {Number} tolerantCfg.num 允许错误像素点数量 默认为10
106     * @return {Boolean} 是否相同
107     */
108    diffImage:function(img0, img1, tolerantCfg){
109        if(img0.width !== img1.width || img0.height !== img1.height){
110            return false;
111        }
112        else{
113            var imgData0 = this.getImageData(img0);
114            var imgData1 = this.getImageData(img1);
115            var diff = pixelmatch(imgData0, imgData1, null, img0.width, img0.height, {threshold: 0.1, includeAA:false});
116            console.log('      (imageDiff:' + diff + ')');
117            return diff;
118        }
119    },
120    /**
121     * 获取图片数据
122     * @param  {Image} img 图片
123     * @return {Array} imageData
124     */
125    getImageData:function(img){
126        this._cacheCanvas = this._cacheCanvas||document.createElement('canvas');
127        var canvas = this._cacheCanvas;
128        canvas.width = img.width;
129        canvas.height = img.height;
130        var ctx = canvas.getContext('2d');
131        ctx.drawImage(img, 0, 0);
132        var data = ctx.getImageData(0, 0, img.width, img.height).data;
133        return data;
134    }
135};
136
137
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)