【发布时间】:2021-01-27 13:29:25
【问题描述】:
我有一个简单的组件。它所做的只是使用 useQuery 获取数据并将其传递给另一个组件。该组件工作正常,但如果不添加此处所述的 hack,我将无法对其进行测试:
我看过MockedProvider requires timeout,这是在 2.5 年前被问到的。有没有其他可用的方法?我不敢相信图书馆团队提倡将 wait/setTimeout 放在单位中!
组件:
export const PROFILE_QUERY = gql`
query {
profile {
roles
}
}
`;
export const Connected = () => {
const { loading, data, error } = useQuery(PROFILE_QUERY);
const setCurrentProfile = (role: string) => {
cachedSettings(getSettings(role));
};
const roles = data?.profile?.roles;
return <Profile {...{ roles, loading, error, setCurrentProfile }} />;
};
测试用例:
import React from 'react';
import { render } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import Profile from '../Profile';
import ConnectedProfile from '..';
import { MockedProvider, MockedResponse } from '@apollo/client/testing';
import { PROFILE_QUERY } from '../Profile.connected';
jest.mock('../Profile', () => {
return jest.fn(() => null);
});
describe('Connected <Profile />', () => {
const renderComponent = (roles: string[] | undefined) => {
const mock: MockedResponse = {
request: {
query: PROFILE_QUERY
},
result: {
data: {
profile: {
roles
}
}
}
};
return render(
<MockedProvider mocks={[mock]} addTypename={false}>
<MemoryRouter>
<ConnectedProfile />
</MemoryRouter>
</MockedProvider>
);
};
it('multiple roles must have been passed', async () => {
renderComponent(['foo', 'bar']);
**//DOCUMENTATION says do following? - will have to wrap rendering in act as well
//await new Promise(resolve => setTimeout(resolve, 0));**
const args = (Profile as jest.Mock).mock.calls[0][0];
expect(args.roles).toEqual(['agent', 'administrator']);
});
it('no roles passed', async () => {
renderComponent(undefined);
//DOCUMENTATION says do following?
//await new Promise(resolve => setTimeout(resolve, 0));
const args = (Profile as jest.Mock).mock.calls[0][0];
expect(args.roles).toEqual(undefined);
});
afterEach(() => (Profile as jest.Mock).mockClear());
});
【问题讨论】:
-
如果 MockedProvider 像那样工作,则需要延迟。测试库鼓励使用 waitFor 以不依赖于实现。
-
WaitFor 是一个很好的策略,但在我的情况下,我真的不想测试由子组件呈现的元素,我只想测试正在传递的道具。
-
waitFor 不限于元素,它适用于任何异步断言。
标签: reactjs unit-testing jestjs apollo-client react-testing-library