【发布时间】:2022-08-16 10:56:56
【问题描述】:
我想使用 blocTest 为我正在测试的 Cubit 函数模拟按键事件。到目前为止,我似乎无法在 BlocTest 中调用 simulateKeyDownEvent,因为它专注于 Bloc/Cubit 而不是小部件。但是,当我模拟 RawKeyDownEvent() 事件时,isKeyPressed 会返回 false,即使它是正确的模拟键?
任何人都知道为什么会发生这种情况以及如何让它显示真实?
我的 cubit 函数使用以下语法:
void handleKeyPress(RawKeyEvent event) {
if (event.isKeyPressed(LogicalKeyboardKey.keyU)) { ... }
...
事件模拟和测试:
blocTest<Cubit, State>(\'Handle key press, increase layer\',
build: () => cubit, // defined in setup
act: (cubit) async {
RawKeyEvent mockEnterKey = const RawKeyDownEventMock(
data: RawKeyEventDataWindows(keyCode: 13, scanCode: 28, characterCodePoint: 0, modifiers: 0), character: \'enter\')
..physicalKey = PhysicalKeyboardKey.enter
..logicalKey = LogicalKeyboardKey.enter;
cubit.handleKeyPress(mockEnterKey);
},
expect: () => [isA<State>().having((state) => state.currentLayer, \'curent layer\', initState + 1)]);
事件模拟定义:
class RawKeyDownEventMock extends RawKeyEvent {
const RawKeyDownEventMock({required data, String? character, bool repeat = false}) : super(data: data, character: character, repeat: repeat);
set physicalKey(PhysicalKeyboardKey key) => key;
set logicalKey(LogicalKeyboardKey key) => key;
@override
bool isKeyPressed(LogicalKeyboardKey key) {
// Showing as false in tests even when simulating key
// logical key id - name - physical key id
// 4294967309 - enter - 458792
// 117 - U - 458776
// 97 - A - 458756
// if (key.keyId == 4294967309 || key.keyId == 117 || key.keyId == 97) return true;
return super.isKeyPressed(key);
}
}
标签: flutter dart testing flutter-bloc flutter-cubit