我正在为一种当用户单击按钮时启动浏览器窗口的方法编写单元测试。
测试失败,因为返回了null
。
运行测试时,不会打开浏览器窗口。
使用该应用程序时,它可以按预期工作。
我已经看到很多其他有关window.open()返回null或不执行OP想要的操作的SO问题,但是这些都与让浏览器执行特定操作有关。在Web应用程序中使用时,我正在测试的代码可以完成我想要做的事情,但是我无法为其编写通过单元测试。此单元测试是解决此方法运行后在步骤中发生的问题的一个步骤,这就是为什么我想了解为什么此测试未通过的原因。
最高答案here使我认为浏览器可能正在阻止新窗口,因为请求来自浏览器外部,这将导致null
返回。我禁用了Chrome中的弹出窗口阻止功能,以防万一。
这是main.dart:
import 'package:flutter_web/material.dart';
import 'dart:html' as html;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Minimal, Reproducible Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
);
}
}
class PrintReports extends StatelessWidget {
const PrintReports({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
RaisedButton(
child: Text(
"Print A Form . . ."
),
color: Colors.blue,
onPressed: () => {
// generate form . . .
// request submission . . .
// launch browser window . . .
},
),
],
);
}
Future launchURL(String download_url)
async {
try {
await html.window.open(download_url, "Get_Submission");
} catch (e) {
print(e);
}
}
}
这是test.dart:
import 'dart:html';
import 'package:flutter_tests/main.dart';
import 'package:test/test.dart';
void main(){
test("_launchURL launches browser at correct URL", () async {
// Arrange: setup the test
PrintReports printReports = PrintReports();
// Act
WindowBase window = await printReports.launchURL("https://someurl.com/download");
// Assert
expect(window, WindowBase);
});
}
要运行测试,我使用以下终端命令:pub run test test/print_reports_card_test.dart -p chrome
。
当前测试结果为:
00:14 +2 -1: _launchURL launches browser at correct URL [E]
Expected: Type:<WindowBase>
Actual: <null>
[ . . . I can post this redacted output if you think it might be relevant . . . ]
00:14 +2 -1: Some tests failed.