gpt4 book ai didi

javascript - 如何在 Jest 中使用回调来模拟 react 导航导航功能

转载 作者:行者123 更新时间:2023-12-01 00:33:01 26 4
gpt4 key购买 nike

我正在尝试使用 jest 测试我的功能组件:

const MyComponent = props => {

const myFunction = () => {
const { navigation, onIndexChange } = props;

navigation.navigate("Modal", {
onGoBack: () => {
onIndexChange(0);
}
});
};

...
}

现在在我的测试中,如果我运行

expect(navigation.navigate).toHaveBeenCalledTimes(1);

它完美地通过了。但我不知道如何模拟 navigate 以便我可以使用 toHaveBeenCalledWith 测试它,基本上我想要这样的东西:

expect(navigation.navigate).toHaveBeenCalledWith("Modal", {onGoBack: onIndexChange(0)});

这就是我目前 mock 它的方式:

const navigation = {
navigate: jest.fn()
};

这就是我尝试使用 toHaveBeenCalledWith 时得到的结果: enter image description here

最佳答案

你的主张

expect(navigation.navigate).toHaveBeenCalledWith("Modal", {onGoBack: onIndexChange(0)});

意味着您期望 navigation.navigate 作为第二个具有 onGoBack 的对象进行调用,该对象具有 onIndexChange 结果的值> 使用 0 调用

但在您的实现中,onGoBack 的值是一个匿名函数

因此,如果您可以断言已使用具有函数的对象调用该函数:

expect(navigation.navigate).toHaveBeenCalledWith("Modal", {
onGoBack: expect.any(Function)
});

每当调用该函数时,它都会调用给定的 onIndexChange

describe('whenever the anonymous function is called', () => {
let onGoBack;
beforeAll(() => {
const [firstCall] = navigation.navigate.mock.calls;
[location, { onGoBack }] = firstCall;
onGoBack()
})

it('should call onIndexChange', () => {
expect(onIndexChange).toHaveBeenCalledWith(0);
});
});

working example (without React)

关于javascript - 如何在 Jest 中使用回调来模拟 react 导航导航功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58350914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com