我有一个简单的 Apollo 设置。在这个 CodeSandbox 示例中,我使用的 MockedProvider是实时的,但也可以使用:
https://codesandbox.io/s/winter-glitter-o8ug5?file=/src/App.js:0-1164
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { gql, useQuery, ApolloProvider } from "@apollo/client";
import { MockedProvider } from "@apollo/client/testing";
const client = new ApolloClient({
uri: "https://48p1r2roz4.sse.codesandbox.io",
cache: new InMemoryCache()
});
const EXCHANGE_RATES_1 = gql`
query GetExchangeRates {
rates(currency: "USD") {
rate
}
}
`;
const mocks = [
{
request: {
query: EXCHANGE_RATES_1
},
result: {
data: {
rates: [
{
__typename: "ExchangeRate",
rate: "123"
}
]
}
}
}
];
const MyComponent = () => {
const { data: data1, loading: loading1 } = useQuery(EXCHANGE_RATES_1);
if (loading1) return <p>Loading...</p>;
return (
<div>
<h1>{data1?.rates[0].rate}</h1>
</div>
);
};
const AppMocked = () => {
return (
<MockedProvider addTypename={false} mocks={mocks}>
<MyComponent />
</MockedProvider>
);
};
const AppLive = () => {
return (
<ApolloProvider client={client}>
<MyComponent />
</ApolloProvider>
);
};
export default AppMocked;
我需要有一个额外useQuery的 in MyComponent。我知道这是一个奇怪的例子,因为它应该只是一个查询,但它说明了我遇到的问题。
https://codesandbox.io/s/magical-dewdney-j451d?file=/src/App.js:0-1630
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { gql, useQuery, ApolloProvider } from "@apollo/client";
import { MockedProvider } from "@apollo/client/testing";
const client = new ApolloClient({
uri: "https://48p1r2roz4.sse.codesandbox.io",
cache: new InMemoryCache()
});
const EXCHANGE_RATES_1 = gql`
query GetExchangeRates {
rates(currency: "USD") {
rate
}
}
`;
const EXCHANGE_RATES_2 = gql`
query GetExchangeRates {
rates(currency: "USD") {
currency
}
}
`;
const mocks = [
{
request: {
query: EXCHANGE_RATES_1
},
result: {
data: {
rates: [
{
__typename: "ExchangeRate",
rate: "123"
}
]
}
}
},
{
request: {
query: EXCHANGE_RATES_2
},
result: {
data: {
rates: [
{
__typename: "ExchangeRate",
currency: "YOLO"
}
]
}
}
}
];
const MyComponent = () => {
const { data: data1, loading: loading1 } = useQuery(EXCHANGE_RATES_1);
const { data: data2, loading: loading2 } = useQuery(EXCHANGE_RATES_2);
if (loading1 || loading2) return <p>Loading...</p>;
return (
<div>
<h1>{data1?.rates[0].rate}</h1>
<h2>{data2?.rates[0].currency}</h2>
</div>
);
};
const AppMocked = () => {
return (
<MockedProvider addTypename={false} mocks={mocks}>
<MyComponent />
</MockedProvider>
);
};
const AppLive = () => {
return (
<ApolloProvider client={client}>
<MyComponent />
</ApolloProvider>
);
};
export default AppMocked;
实时版本运行良好,但模拟版本的 H1 为空。当我注销时,data1我可以看到它最初确实有数据,但在随后的渲染中变为“未定义”
我在文档中看不到任何东西来解释为什么模拟不起作用:https ://www.apollographql.com/docs/react/development-testing/testing/