Apollo Boost MockedProvider在查询中使用片段时返回空对象



我有一个使用Apollo BoostMockedProvider、Jest和React测试库的工作测试,当我将返回的字段更改为graphQLfragment时,它将停止工作。我错过了什么?

TicketGql.js

export default class TicketGql {
static VIEW_FRAGMENT = gql`
fragment ViewFragment on View {
viewId
versionId
name
description
orderedColumns {
columnId
name
descriptions {
translationId
lang
description
}
}
}
`;
static GET_TICKET_VIEW = gql`
query getView($viewId: ID!) {
view(viewId: $viewId) {
viewId
versionId
name
description
orderedColumns {
columnId
name
descriptions {
translationId
lang
description
}
}
}
}
`;
}

TicketGql.test.js

...
it('GET_TICKET_VIEW', async () => {
const currentLang = uniqid('lang_');
const viewMock = {
viewId: uniqid('viewId_'),
versionId: uniqid('versionId_'),
name: uniqid('name_'),
description: uniqid('description_'),
orderedColumns: [],
};
_.times(_.random(1, 5), (columnIndex) => {
viewMock.orderedColumns.push({
columnId: uniqid('columnId_'),
name: uniqid('columnId_'),
descriptions: [],
});
_.times(
_.random(1, 3),
(descIndex) => viewMock.orderedColumns[columnIndex].descriptions.push({
translationId: uniqid('translationId_'),
lang: descIndex === 0 ? currentLang : uniqid('lang_'),
description: uniqid('description_'),
}),
);
});
const variables = { viewId: viewMock.viewId };
const mocks = [
{
request: {
query: TicketGql.GET_TICKET_VIEW,
variables,
},
result: {
data: {
view: viewMock,
},
},
},
];
const TicketViewColumns = () => {
const { data, loading, error } = useQuery(TicketGql.GET_TICKET_VIEW, {
variables,
});
return (
<div>
{error}
<ul>
{
loading
? 'loading...'
: (
data.view.orderedColumns.map((column) => (
<li key={column.columnId}>
{column.descriptions.find((d) => d.lang === currentLang).description}
</li>
))
)
}
</ul>
</div>
);
};
render(
<MockedProvider mocks={mocks} addTypename={false}>
<TicketViewColumns />
</MockedProvider>,
);
await waitFor(() => expect(screen.queryAllByRole('listitem'))
.toHaveLength(viewMock.orderedColumns.length));
);
...

此测试按原样运行。但是,当我将GET_TICKET_VIEW更改为。。。

static GET_TICKET_VIEW = gql`
query getView($viewId: ID!) {
view(viewId: $viewId) {
...ViewFragment
}
}
${TicketGql.VIEW_FRAGMENT}
`;

它就停止工作了。MockedProvide返回data === { view: {} }而不是viewMock中提供的数据,导致data.view.orderedColumns.map出现错误,因为data.view.orderedColumnsundefined。我用这个片段做了另一个突变测试,它有效。

编辑:

软件包.json

"dependencies": {
"@apollo/react-hooks": "^4.0.0",
"apollo-boost": "^0.4.9",
"graphql": "^15.0.0",
...
}
"devDependencies": {
"@apollo/client": "^3.1.1",
"@testing-library/jest-dom": "^5.8.0",
"@testing-library/react": "^10.0.4",
...
}

使用片段时,只需将__typename添加到mock对象中。对于没有碎片/联合的简单查询来说,它不是必需的,但如果你有它,它是必需的

点击此处阅读更多

最新更新