在测试ReactJs助手时,我找不到模拟对象导入的方法。所有的例子都展示了如何模拟导入的函数,而没有人谈论模拟导入的对象。
我想模拟的这个基本帮助对象:
filters-state.helper.ts
:
export const FiltersStateHelper = {
toggleFilters: <T extends FiltersState>(state: T): T => ({
...state,
isOpen: !state.isOpen
})
};
我正在测试的状态助手中使用它:
search-view-state.helper.ts
:
import { FiltersStateHelper } from 'shared/filters/helpers/filters-state.helper';
export const SearchViewStateHelper = {
toggleFilters: <T extends SearchViewState>(state: T): T => ({
...state,
filters: FiltersStateHelper.toggleFilters(state.filters)
})
//... more methods
};
在测试中,嘲讽依赖性失败了,可能是因为我的助手的依赖性在我说嘲笑什么之前就已经解决了:
search-view-state.helper.spec.ts
:
import { SearchViewStateHelper as helper } from 'shared/search-view/helpers/search-view-state.helper';
describe('toggleFilters method', () => {
const spy = jest.fn();
jest.doMock('shared/filters/helpers/filters-state.helper', () => {
return {
toggleFilters: spy
};
});
const state = {};
it('should toggle filters', () => {
helper.toggleFilters(state);
expect(spy).toHaveBeenCalled();
});
});
您可以使用jest.spyOn(object,methodName,accessType?(监视FiltersStateHelper
对象的toggleFilters
方法。
例如
filters-state.helper.ts
:
type FiltersState = any;
export const FiltersStateHelper = {
toggleFilters: <T extends FiltersState>(state: T): T => ({
...state,
isOpen: !state.isOpen
})
};
search-view-state.helper.ts
:
import { FiltersStateHelper } from './filters-state.helper';
type SearchViewState = any;
export const SearchViewStateHelper = {
toggleFilters: <T extends SearchViewState>(state: T): T => ({
...state,
filters: FiltersStateHelper.toggleFilters(state.filters)
})
// ... more methods
};
search-view-state.helper.spec.ts
:
import { SearchViewStateHelper as helper } from './search-view-state.helper';
import { FiltersStateHelper } from './filters-state.helper';
describe('toggleFilters method', () => {
const state = { filters: { isOpen: false } };
it('should toggle filters', () => {
const spy = jest.spyOn(FiltersStateHelper, 'toggleFilters');
helper.toggleFilters(state);
expect(spy).toHaveBeenCalled();
expect(spy).toBeCalledWith({ isOpen: false });
});
});
100%覆盖率的单元测试结果:
PASS src/stackoverflow/58746881/search-view-state.helper.spec.ts
toggleFilters method
✓ should toggle filters (6ms)
-----------------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
filters-state.helper.ts | 100 | 100 | 100 | 100 | |
search-view-state.helper.ts | 100 | 100 | 100 | 100 | |
-----------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.833s, estimated 8s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58746881