我在模拟调用单独导入的函数到我的测试时遇到了问题。这个测试是一个简单的函数,我将它放在Redux操作中,以便能够根据条件设置变量。
下面是Body.duck.js中的函数:
export const getCurrentOrPrevSelection = isExecutedFromPagination => (dispatch, getState) => {
const {
editor: { selection },
body: { queryRequest },
} = getState();
if (isExecutedFromPagination && queryRequest.breadcrumb) {
const {
query: { branch, includeSplits, primaryFa, split, isInitial },
} = queryRequest.breadcrumb;
return {
branch,
includeSplits,
primaryFa,
split,
isInitial,
};
}
return selection;
};
下面是测试文件:
import reudcer, { ...other exported functions, getCurrentOrPrevSelection } from '../Body.duck';
it ('should use selection in breadcrumb state when fetching new data from pagination action', () => {
let isExecutedFromPagination = false;
const bodyState = {
...initialState.body,
queryRequest: {
...initialState.body.queryRequest,
breadcrumb: {
...initialState.body.breadcrumb,
query: {
name: 'Full Book Performance',
branch: null,
includeSplits: true,
primaryFa: 'AXFO',
split: null,
isInitial: true,
},
},
},
};
const selection = {
branch: null,
includeSplits: true,
primaryFa: 'AXFO',
split: null,
isInitial: true,
};
expect(getCurrentOrPrevSelection(isExecutedFromPagination)(jest.fn(), () => ({
body: { ...bodyState },
editor: { faidSelection },
}))).toHaveReturnedWith({
branch: null,
includeSplits: true,
primaryFa: 'AXFO',
split: null,
isInitial: true,
});
});
如果我没有包含任何类型的对getCurrentOrPrevSelection的模拟引用,我会得到下面的错误,但它会像预期的那样返回正确的值:
expect(jest.fn())[.not].toHaveReturnedWith()
jest.fn() value must be a mock function or spy.
Received:
object: {"branch": null, "includeSplits": true, "isInitial": true, "primaryFa": "AXFO", "split": null}
如果我执行类似于getCurrentOrPrevFaidSelection = jest.fn();
的操作,我会收到错误消息getCurrentOrPrevFaidSelection is read-only
在这里我可以做些什么不同的事情?
发布于 2019-08-03 16:54:35
您想要测试这个函数。所以你不需要嘲笑它。
只需调用函数并使用expect().toEqual
或expect().toMatchObject
验证结果即可。
expect(getCurrentOrPrevSelection(isExecutedFromPagination)(.....)).toMatchObject({
branch: null,
...
});
另外,直接将jest.fn()
作为参数传递并没有实际意义:您既不能验证它是否已被调用,也不能提供模拟返回。
const dispatchMock = jest.fn();
expect(getCurrentOrPrevSelection(isExecutedFromPagination)(dispatchMock, ....);
expect(dispatchMock).toHaveBeenCalledWith(...)
一旦不希望像在示例中那样调用它,您最好显式地提供noop函数() => {}
而不是jest.fn()
。通过这种方式,您可以使其显式,因此,如果预期没有针对此函数的断言,则没有人会感到困惑。
Offtop:实际上,这并不是测试redux动作创建器的好方法。请看你实际测试实现的细节。如果您从redux-thunk
迁移到redux-saga
或redux-loop
,该怎么办?或者将单个操作拆分为两个,以获得更好的灵活性?到目前为止,这意味着你必须重写所有的测试。
如果不是孤立地测试action creator,而是将action连接到真正的(而不是模拟的)存储呢?您可以分派操作(在模拟对外部API的调用之后)并验证存储的状态。
https://stackoverflow.com/questions/57329839
复制相似问题