Search code examples
flutterflutter-webflutter-testflutter-web-browser

How to injest javascript in


I'm working on a Flutter web project. The web/index.html file is injecting a JavaScript script which could be simplified as:

<script>
  window['dataLayer'] = [];
</script>

So in my flutter code, I can do:

@JS()
import 'package:js/js.dart';

@JS('dataLayer.push')
external void push(data);

push(myData);

to push myData in the window.dataLayer array.

However, in the tests, when I'm running

flutter test --platform chrome

I'm getting the error

TypeError: Cannot read properties of undefined (reading 'push')

when I call

push(myData);

because window['dataLayer'] has never been created.


How can I inject some javascript scripts the same way I can do in the index.html?


Solution

  • It is possible to load a custom HTML file while running the tests, see the instructions of the package test.

    If your test file name is folder/my_test.dart, then you can create a html file named (folder/my_test.html):

    <!doctype html>
    <html>
    
    <head>
      <title>Custom HTML file title</title>
      <link rel="x-dart-test" href="my_test.dart">
      <script src="packages/test/dart.js"></script>
      <script>
        window['dataLayer'] = [];
      </script>
    </head>
    
    </html>
    

    See this StackOverflow question.

    and then you can run

    dart test --platform chrome
    

    However, this is only supported with dart test and not flutter test, see this issue. In it, they recommend writing an integration test instead.