这是我正在测试的组件的测试文件。它发出片段警告,但不起作用。我在查询未使用fragment
的另一个组件上使用了相同的代码,并且可以正常工作。我不知道如何测试使用fragment
的查询的组件。我现在觉得好蠢。这是我第三次尝试测试。
__Typename
是错误的,我已经检查了其他答案。他们都没有帮助我。
React-Apollo
测试非常困难:/
import React from 'react';
import {
wait,
cleanup,
waitForElement,
fireEvent
} from '@testing-library/react';
import { Route } from 'react-router';
import { customRender } from '../../test-utils/customRender';
import { CategoriesListContainer } from './list/Container';
import { getAllCategoriesQuery } from '../../queries/GET_ALL_CATEGORIES';
import { reorderCategoriesMutation } from '../../queries/REORDER_CATEGORIES';
afterEach(() => {
cleanup();
// @ts-ignore
console.error.mockClear();
});
console.error = jest.fn();
const getAllCategoriesMock = {
request: {
query: getAllCategoriesQuery
},
result: {
data: {
getAllCategories: [
{
id: 1,
name: 'categoryName',
thumbnail: undefined,
position: 1,
active: false,
created_at: 1,
updated_at: 1,
__typename: 'Category'
}
]
}
}
};
const reorderCategoriesMock = {
request: {
query: reorderCategoriesMutation,
variables: {
category_ids: [1, 2]
}
},
result: {
data: {
reorderCategories: true
}
}
};
describe('Category module testing', () => {
test('Category List', async () => {
const { container, getByText, findByText, debug } = customRender(
<Route path="/">
<CategoriesListContainer />
</Route>,
[getAllCategoriesMock, reorderCategoriesMock]
);
const tagName = await waitForElement(() => getByText(`categoryName`));
const createdAt = await waitForElement(() =>
getByText(`01/01/1970 05:30:00`)
);
expect(createdAt).toBeDefined();
expect(container).toMatchSnapshot();
expect(tagName).toBeDefined();
});
});
这是我的customRender:
import * as React from 'react';
import { render, cleanup } from '@testing-library/react';
import { MockedProvider, MockedResponse } from '@apollo/react-testing';
import { Router, Switch } from 'react-router-dom';
import { createMemoryHistory } from 'history';
afterEach(cleanup);
export const customRender = (
node: JSX.Element | null,
mocks?: MockedResponse[],
{
//@ts-ignore
route = '/',
history = createMemoryHistory({ initialEntries: [route] })
} = {}
) => {
return {
history,
...render(
<MockedProvider mocks={mocks} addTypename={false}>
<Router history={history}>
<Switch>{node}</Switch>
</Router>
</MockedProvider>
)
};
};