我正在尝试对名为search
的方法进行单元测试,该方法具有三种方法,例如buildSearchParameter
,isUnknownFields
,readAll
。我需要嘲笑他们,但我不知道该怎么做。有人可以帮我吗?
search = async (=> {
const searchParam = buildSearchParameter();
// check for unknown fields
const isUnknownFields = isUnknownFields();
readAll()
})
答案 0 :(得分:1)
为简化问题,我删除了它的静态类型。您可以使用Expanded(child:
Column(
children: <Widget>[
Container(
height: 50,
width: MediaQuery.of(context).size.width * 0.8,
child:
Text(snapshot.data.documents[index]['title']),
),
Container(
height: 50,
width: MediaQuery.of(context).size.width * 0.8,
child:
Text(snapshot.data.documents[index]['body']),
),
],
),
),
为这三种方法创建存根。这是单元测试解决方案:
jest.spyOn
:
index.ts
import ModelUtility from './ModelUtility';
enum EndpointType {
SEARCH = 'SEARCH',
}
export class SomeClass {
schemaConstants;
errorConstants = {
invalidQueryParameters: 'invalid',
};
search = async (query, endpointConstants) => {
const searchParam = ModelUtility.buildSearchParameter(query, endpointConstants, this.schemaConstants);
// check for unknown fields
const isUnknownFields = ModelUtility.isUnknownFields(EndpointType.SEARCH, searchParam, this.schemaConstants);
if (isUnknownFields) {
return this.errorConstants.invalidQueryParameters;
}
return this.readAll(query, searchParam, endpointConstants);
};
readAll(...args) {
return 'real data';
}
}
:
ModelUtility.ts
export default {
buildSearchParameter(...args) {
return 'real search parameter';
},
isUnknownFields(...args) {
return true;
},
};
:
index.spec.ts
带有覆盖率报告的单元测试结果:
import { SomeClass } from './';
import ModelUtility from './ModelUtility';
describe('SomeClass', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should return invalid query parameters', async () => {
const buildSearchParameterSpy = jest
.spyOn(ModelUtility, 'buildSearchParameter')
.mockReturnValueOnce('mocked search parameter');
const isUnknownFieldsSpy = jest.spyOn(ModelUtility, 'isUnknownFields').mockReturnValueOnce(true);
const instance = new SomeClass();
const actual = await instance.search('mocked query', 'endpointConstants');
expect(actual).toBe('invalid');
expect(buildSearchParameterSpy).toBeCalledWith('mocked query', 'endpointConstants', undefined);
expect(isUnknownFieldsSpy).toBeCalledWith('SEARCH', 'mocked search parameter', undefined);
});
it('should return correctly', async () => {
const buildSearchParameterSpy = jest
.spyOn(ModelUtility, 'buildSearchParameter')
.mockReturnValueOnce('mocked search parameter');
const isUnknownFieldsSpy = jest.spyOn(ModelUtility, 'isUnknownFields').mockReturnValueOnce(false);
const instance = new SomeClass();
jest.spyOn(instance, 'readAll').mockReturnValueOnce('mocked data');
const actual = await instance.search('mocked query', 'endpointConstants');
expect(actual).toBe('mocked data');
expect(buildSearchParameterSpy).toBeCalledWith('mocked query', 'endpointConstants', undefined);
expect(isUnknownFieldsSpy).toBeCalledWith('SEARCH', 'mocked search parameter', undefined);
});
});