【发布时间】:2018-04-10 13:25:18
【问题描述】:
我有以下设置来测试异步函数。
首先,我的文件夹结构:
src/
├── App.vue
├── api
│ ├── __mocks__
│ │ └── api.js
│ └── api.js
├── components
│ ├── ...
├── main.js
└── store
├── __tests__
│ └── actions.spec.js
├── actions.js
├── getters.js
├── index.js
├── mutation-types.js
└── mutations.js
然后我的actions.spec.js:
import * as types from '@/store/mutation-types';
import api from '@/api/api';
import {
fetchItems,
requestItems,
saveQuestion,
vote,
} from '../actions';
jest.mock('@api/api');
describe('fetchItems Action', () => {
let state;
let commit;
let dispatch;
beforeAll(() => {
commit = jest.fn();
dispatch = jest.fn();
state = {
apiEntryPoint: '',
nextPage: 0,
};
});
beforeEach(() => {
fetchItems({
commit,
dispatch,
state,
});
});
it('should call a commit before fetching', () => {
expect(commit).toHaveBeenCalledWith(types.PRE_HTTP_REQUEST);
});
it('should call receiveItems after succesful fetch', () => {
setTimeout(() => {
expect(dispatch).toHaveBeenCalledWith('receiveItems', {});
});
});
it('should call a fail commit if request fails', () => {
api.fetchItems = jest.fn(() => Promise.reject());
setTimeout(() => {
expect(commit).toHaveBeenCalledWith(types.FETCHED_ADS_FAIL);
});
});
});
api/api.js
import axios from 'axios';
axios.defaults.baseURL = 'https://polls.apiblueprint.org/';
const getUrl = () => (
axios('/')
.then(response => response.data.questions_url)
.catch((err) => {
throw err;
})
);
const fetchItems = (url, page = 1) => (
axios(url, { params: { page } })
.then(response => response.data)
.catch((err) => {
throw err;
})
);
export default {
fetchItems, getUrl,
};
还有api/__mocks__/api.js
const getUrl = jest.fn(() => Promise.resolve());
const fetchItems = jest.fn(() => Promise.resolve());
export default {
fetchItems, getUrl
};
我的问题:
- 通过使用调试器,它看起来不像在运行模拟方法
- 我的输出看起来像一个真正的 HTTP 请求完成了:
PASS src/components/QuestionsList/QuestionsList.spec.js 通过 src/components/Question/Question.spec.js (节点:48568)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:9):错误:错误:网络错误 (节点:48568)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。在未来,承诺拒绝是 未处理将以非零退出终止 Node.js 进程 代码。 (节点:48568)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:10):错误:错误:网络错误 通过 src/store/tests/actions.spec.js
- 即使我用其他随机参数更改“
toHaveBeenCalledWith()”的参数,我的测试也通过了。
【问题讨论】: