【发布时间】:2020-01-03 21:48:37
【问题描述】:
免责声明;我对 react-testing-library (一直在使用公认的旧版本的 Enzyme)和 Apollo Query/MockedProvider 组件(通过 JS 服务对象使用客户端)有点新,所以这可能是一个愚蠢的问题.. .
我有一个组件,它接收我正在尝试为其编写测试的国家/地区列表。我想做的是:
import React from 'react';
import { MockedProvider } from '@apollo/react-testing';
import { render, act } from '@testing-library/react';
import wait from 'waait';
import Countries, { countryQuery } from './Countries';
import { isTerminating } from 'apollo-link/lib/linkUtils';
const mockCountryName = 'sample country';
const mocks = [
{
request: {
query: countryQuery,
vairables: {},
},
result: {
data: {
countries: [{ name: mockCountryName }],
},
},
},
];
describe('when working with the countries component', () => {
describe('and the component is loading', () => {
let component;
beforeAll(async (done) => {
await act(async () => {
component = render(
<MockedProvider mocks={[]}>
<Countries />
</MockedProvider>
);
});
done();
});
it('should have a title', () => {
expect(component.getByText('Countries Component')).not.toBeUndefined();
});
it('should have a loading status', () => {
expect(component.getByText('Loading...')).not.toBeUndefined();
});
});
});
当它运行时,第二个测试(关于加载状态)失败,因为此时组件看起来只是一个 body 标签。我尝试将 beforeAll 更改为 beforeEach,但这只是产生了一个带有错误指示器的组件。我在我的组件中放了一些 console.log 语句,这就是它们向我展示的内容:
console.log src/components/Countries.js:45
Loading is: true
console.log src/components/Countries.js:46
Error is: undefined
console.log src/components/Countries.js:45
Loading is: false
console.log src/components/Countries.js:46
Error is: Error: Network error: No more mocked responses for the query: {
countries {
name
phone
__typename
}
}
, variables: {}
我想知道它是否不喜欢作为 MockedProvider 的模拟属性传入的空数组。但是我看到的每个例子都是这样的,所以......
作为一项实验,我在规范文件中添加了第二组测试,以查看导致问题的组件是否只是一个奇怪的计时问题。这是第二个测试:
describe('and the component has data', () => {
let component;
beforeAll(async (done) => {
await act(async () => {
component = render(
<MockedProvider mocks={mocks} addTypename={false}>
<Countries />
</MockedProvider>
);
await wait(0);
});
done();
});
it('should have a title', () => {
expect(component.getByText('Countries Component')).not.toBeUndefined();
});
it('should have a loading status', () => {
expect(component.getByText(mockCountryName)).not.toBeUndefined();
});
});
这有同样的问题;第一个测试有效(如果我重新排序测试,第一个总是有效的)但第二个失败,并且组件似乎是一个空的正文标签。
有没有办法让这种类型的测试结构发挥作用?我不喜欢将所有内容都放在一个测试中的想法,更不用说组件的设置代码了。
谢谢!
【问题讨论】:
标签: javascript reactjs jestjs apollo-client react-testing-library