gpt4 book ai didi

javascript - 如何测试使用 useQuery 的组件的示例?

转载 作者:搜寻专家 更新时间:2023-11-01 04:34:30 27 4
gpt4 key购买 nike

我有一个使用 Apollo 钩子(Hook)库的 useQuery 钩子(Hook)的 React 组件。我在测试此组件时遇到问题。这是我当前的设置。

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import DashboardBar from './DashboardBar';
import { render, cleanup } from '@testing-library/react';
import { QUERY } from '../../queries';
import { ApolloClient } from 'apollo-client';
import { ApolloProvider as ApolloHooksProvider } from '@apollo/react-hooks';
import { MockedProvider } from 'react-apollo/test-utils';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { MockLink } from 'apollo-link-mock';
import wait from 'waait';
import casual from 'casual';

describe('<DashboardBar />', () => {
it('renders and matches snapshot', async () => {
const mocks = [
{
request: { query: QUERY, variables: { id: 'WLYhM' } },
result: {
data: {
q: {
brand: fakeBrand,
claimByAction: casual.boolean,
claimRules: fakeClaimRules,
wantIn: fakeWantIn,
},
},
},
},
];

function createClient(mocks) {
return new ApolloClient({
cache: new InMemoryCache(),
link: new MockLink(mocks),
});
}

const client = createClient(mocks);

const { container } = render(
<ApolloHooksProvider client={client}>
<Router>
<DashboardBar {...props} store={reduxStore.store} />
</Router>
</ApolloHooksProvider>
);

console.log(container.firstChild);
expect(container.firstChild).toBe(null);

await wait(200);

console.log(container.firstChild);
});
});

当我运行测试时,出现以下错误

TypeError: 无法读取未定义的属性“q”

即使数据在实际组件中正常返回。

有没有人举例说明如何使用来自 Apollo Hook 库的 Hook 成功设置和执行带组件的测试?

谢谢!

最佳答案

实际上,我设法使用 act()

实现了这一点

示例如下:

import { MockedProvider } from '@apollo/react-testing'
import query from 'data/graphql/Device/psaButton.graphql'
import React from 'react'
import { act, create, ReactTestRenderer } from 'react-test-renderer'
import { MockAppNoLayout } from 'testHelpers/testHelpers'
import waitForExpect from 'wait-for-expect'
import PSAButton from './PSAButton'

const mocks = [
{
request: {
query,
variables: {
deviceId: '1',
},
},
result: {
data: {
deviceById: {
id: '1',
info: {
psaUrl: 'asdsadsad',
lastSyncDate: 'asdasd',
lastVerifyDate: 'asdsad',
},
},
user: {
timeZone: 'Europe/London',
},
},
},
},
]

describe('PSAButton', () => {
it('renders correctly', async () => {
let wrapper: ReactTestRenderer
act(() => {
wrapper = create(
<MockAppNoLayout>
<MockedProvider mocks={mocks} addTypename={false}>
<PSAButton deviceId="1" />
</MockedProvider>
</MockAppNoLayout>,
)
})

await waitForExpect(() => {
const testInstance = wrapper.root
expect(testInstance.findByType('span').children[0]).toBe('Open In PSA')
})
})
})

MockAppNoLayout 是一个包含 amock IntlProviderStyleprovider 等的 React 组件树,(对于这个问题不重要)。

关于javascript - 如何测试使用 useQuery 的组件的示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57060842/

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