进行异步调用的thunk
buyerAction = (data = {}, cb) => (dispatch) => {
console.log('x-access-token', authService.getAccessToken());
axios({
method: 'POST',
url: `http://localhost:3001/api/manageUsers`,
headers: {
'x-access-token': authService.getAccessToken()
},
data
}).then((res) => {
if (res.status === 200 && res.data) {
dispatch({ type: 'buyer_created', data: res.data.message });
if (data.role === 'buyer') {
axios({
method: 'POST',
url: `http://localhost:3001/api/populateBuyerLookUp`,
headers: {
'x-access-token': authService.getAccessToken()
},
data
}).then((response) => {
console.log(`${response} lookup is created`);
}).catch((err) => { console.log(err); });
}
cb(res.data.message);
}
})
.catch((err) => { console.log('_+_+_+', err); });
};
试图测试:
const middleware = [thunk];
const mockStore = configureMockStore(middleware);
describe('Async Actions', () => {
const host = 'http://localhost';
axios.defaults.host = host;
axios.defaults.adapter = httpAdapter;
afterEach(() => {
nock.cleanAll();
});
it('should create Async and load data', (done) => {
nock('http://localhost:3001', {
reqheaders: {
'x-access-token': 'authtoken'
}
})
.post('/api/manageUsers')
.reply(200, { body: { name: 'prakash' } });
const store = mockStore({}, [{ type: 'buyer_created', data: 'message' }]);
store.dispatch(buyerAction(undefined, () => {}));
done();
});
});
错误:x-access-token未定义 TypeError [ERR_HTTP_INVALID_HEADER_VALUE]:无效值"未定义"标题" x-access-token"
我试图用nock测试thunk,有没有更好更简单的方法来测试thunk和mock头?