我有以下测试异步函数的设置。
首先,我的文件夹结构:
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
};我的问题:
传递src/components/QuestionsList/QuestionsList.spec.js,传递src/components/Question.spec.js(节点:48568) UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝id: 9):错误:错误:网络错误(节点:48568) DEP0018 DeprecationWarning:未处理的承诺拒绝被取消。在未来,承诺不处理的拒绝将使用非零退出代码终止Node.js进程。(节点:48568) UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝id: 10):错误:错误:网络错误通过UnhandledPromiseRejectionWarning
toHaveBeenCalledWith()“参数,我的测试也会通过。发布于 2017-10-29 21:07:09
在使用setTimeout进行测试时,需要使用done回调。
目前,Jest正在运行测试并无错误地到达终点。对Jest来说,这意味着测试已经通过。让Jest异步运行测试的一种方法是使用done回调。
如果测试有已完成的回调,Jest将在已完成的回调被调用之前不会通过测试。
您的代码应该如下所示:
it('should call a fail commit if request fails', (done) => {
api.fetchItems = jest.fn(() => Promise.reject());
setTimeout(() => {
expect(commit).toHaveBeenCalledWith(types.FETCHED_ADS_FAIL);
done()
});
});您可以在Jest (http://facebook.github.io/jest/docs/en/asynchronous.html#callbacks)中阅读[已完成的回调“。
Jest还有其他几种与异步码打交道的方式。
发布于 2019-12-14 14:58:18
如果有人遇到这种情况,需要在发生这种情况时构建一个失败的解决方案,下面是我已经解决了这个问题:处理UnhandledPromiseRejectionWarning错误
https://stackoverflow.com/questions/47000453
复制相似问题