这是我如何使用 MockedProvider。如何在 mocks 数组中模拟 refetch?
const mocks = [{
request: {
query: GET_USERS_BY_FACILITY,
variables: {
facility: 300
}
},
result: {
data: {
GetUsersByFacility: [{
nuId: 'Q916983',
userName: faker.internet.userName(),
profileKey: 'testKey',
profileValue: 'testValue',
__typename: 'FacilityUser'
}]
}
},
refetch: () => {
return {
data: {
GetUsersByFacility: [{
nuId: 'Q916983',
userName: faker.internet.userName(),
profileKey: 'testKey',
profileValue: 'testValue',
__typename: 'FacilityUser'
}]
}
}
}
}
此测试用例在触发删除事件时调用 refetch 函数。
it('should be able to click on delete user', async () => {
const {getByTestId} = render(
<MockedProvider mocks={mocks}>
<Users selectedFacility={300}/>
</MockedProvider>)
await wait(0)
fireEvent.click(getByTestId('btnDelete'))
})
我一直在尝试不同的方法,似乎都不起作用。我收到错误消息 类型错误:无法读取未定义的属性“refetch” .
非常感谢,希望得到答复。
问候,
——拉贾尼
最佳答案
也许现在回答有点晚了,但如果你还没有得到任何答案,你可以引用我解决的方式。
请注意,这可能不是正确答案。
const mocks = [
{
request: {
query: GET_DOG_QUERY,
variables: {
name: 'Buck',
},
},
result: () => {
// do something, such as recording that this function has been called
// ...
return {
data: {
dog: { id: '1', name: 'Buck', breed: 'bulldog' },
},
}
},
},
];
// do something, such as recording that this function has been called
这是我的模拟示例。
let queryCalled = false
const testingData = (value) => ({
data: {....}
})
const TESTING_MOCK = {
request: {
query: TESTING_QUERY,
variables: { some: "variables" },
},
result: () => {
if (queryCalled) return testingData("refetched");
else {
queryCalled = true;
return testingData("first fetched");
}
},
};
=> 在上面的代码中,
queryCalled
是 false
所以,它重新分配 queryCalled
如 true
并返回“第一次获取”的模拟数据,=> 基于同样的原则,模拟数据返回“重新获取”的模拟数据。
我的测试代码示例在这里
it("refetch when clicked save button.", async () => {
const mocks = [TESTING_MOCK];
let utils: RenderResult = render(<SomeTestingComponent mocks={mocks} />);
await waitForNextTick(); //for getting a data, not loading
const titleInput = utils.getByDisplayValue("first fetched");
const saveBtn = utils.getByText("save");
fireEvent.click(saveBtn);
await waitForElement(() => utils.getByDisplayValue("refetched"));
})
如果您有任何其他建议,请告诉我!
关于reactjs - 有没有办法在 MockedProvider - Apollo Client 中模拟 refetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58981274/