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?
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):See this StackOverflow question.
and then you can run
However, this is only supported with
dart testand notflutter test, see this issue. In it, they recommend writing an integration test instead.