我们有一个像这样的选择器工厂:
const selectItems = state => state.items
const selectCategory = state => state.category
const makeSelectItemsByCategory = () => {
const selectItemsByCategory = createSelector(
[selectItems, selectCategory],
(items, category) => items.filter(item => item.category === category)
)
return selectItemsByCategory
}
它正在我试图测试的文件中使用。
...
const itemsByCategory = makeSelectItemsByCategory()(getState())
// do stuff with this...
现在,在我的测试文件中,我尝试模拟
makeSelectItemsByCategory
函数,并且通常会执行以下操作:
jest.mock('/path/to/selector/file', () => ({
makeSelectItemsByCategory: jest.fn()
}))
describe('my-file-name', () => {
beforeEach(() => { jest.resetAllMocks() })
it('does stuff', () => {
jest.mocked(makeSelectItemsByCategory).mockReturnValueOnce(() => []) // error here
....
})
})
换句话说,我想模拟
makeSelectItemsByCategory
的返回值是一个返回空列表的函数。
但是,我在
mockReturnValueOnce
的参数上收到红色波浪线错误:
类型 '() => never[]' 的参数不可分配给以下参数 类型 '((state: TReduxState) => any[]) & OutputSelectorFields<(args_0: TMyType[]) => any[], {clearCache: () => void; }> & { ...; }'。 类型“() => never[]”不可分配给类型“OutputSelectorFields<(args_0: TMyType[]) =>any[], {clearCache:() => 无效; }>'.ts(2345)
任何帮助将不胜感激。
您可以使用
createSelector
创建模拟选择器。
import { createSelector } from 'reselect';
import { makeSelectItemsByCategory } from './selector';
jest.mock('./selector', () => ({
makeSelectItemsByCategory: jest.fn(),
}));
describe('my-file-name', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('does stuff', () => {
const selectItemsByCategoryMock = createSelector(
() => undefined,
() => [1, 2, 3],
);
jest.mocked(makeSelectItemsByCategory).mockReturnValueOnce(selectItemsByCategoryMock);
const itemsByCategory = makeSelectItemsByCategory()({});
expect(itemsByCategory).toEqual([1, 2, 3]);
});
});