Asynchronous 在异步操作创建者中使用nock测试POST请求
我用nock来嘲笑我的异步thunk动作创建者。对于GET请求,一切都按预期工作,但我无法使POST请求工作。我已经阅读了所有我能在网上找到的东西,但是没有任何东西能解决我的问题。我可以在失败的测试运行中看到响应主体。问题是url没有nock匹配。有人能发现问题吗 测试文件:Asynchronous 在异步操作创建者中使用nock测试POST请求,asynchronous,testing,redux,fetch,nock,Asynchronous,Testing,Redux,Fetch,Nock,我用nock来嘲笑我的异步thunk动作创建者。对于GET请求,一切都按预期工作,但我无法使POST请求工作。我已经阅读了所有我能在网上找到的东西,但是没有任何东西能解决我的问题。我可以在失败的测试运行中看到响应主体。问题是url没有nock匹配。有人能发现问题吗 测试文件: describe('#saveReminder', () => { it(`creates ${constants.actions.REQUEST_SAVE_REMINDER} and ${con
describe('#saveReminder', () => {
it(`creates ${constants.actions.REQUEST_SAVE_REMINDER}
and ${constants.actions.RECEIVE_SAVE_REMINDER}`, () => {
data = { payload: 'payload' };
nock(constants.paths.API_AUTHORITY)
.post('api/prospect/add-reminder', {
prospect: 1,
reminder_datetime: '2017-12-22T18:42:00.000Z',
description: 'description',
})
.reply(200, { data } )
const expectedActions = [
{ type: constants.actions.REQUEST_SAVE_REMINDER },
{ type: constants.actions.RECEIVE_SAVE_REMINDER, data }
]
return store.dispatch(actions.saveReminder({
id: 1,
description: 'description',
date: moment(),
time: moment(),
})).then(() => {
expect(store.getActions()).toEqual(expectedActions)
})
})
})
异步操作:
export function saveReminder({ id, description, date, time }) {
return (dispatch) => {
requestSaveReminder();
return fetch(`${constants.paths.API_AUTHORITY}api/prospect/add-reminder`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Csrf-Token': Cookie.get('X-Csrf-Token'),
},
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(
{
prospect: id,
reminder_datetime: moment(`${date.format('MM/DD/YYYY')} ${time.format('HH:mm')}`, 'MM/DD/YYYY HH:mm'),
description,
}
),
}).then(response => {
response.json();
})
.then(json => dispatch(receiveSaveReminder(json.data)))
.catch(ex => dispatch(requestSaveReminderFailure(ex)));
};
}
测试失败:
Object {
- "type": "REQUEST_SAVE_REMINDER",
+ "data": [FetchError: request to http://localhost:8080/api/prospect/add-reminder failed, reason: Nock: No match for request {
+ "method": "POST",
+ "url": "http://localhost:8080/api/prospect/add-reminder",
+ "headers": {
+ "accept": [
+ "application/json"
+ ],
+ "content-type": [
+ "application/json"
+ ],
+ "accept-encoding": [
+ "gzip,deflate"
+ ],
+ "user-agent": [
+ "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
+ ],
+ "connection": [
+ "close"
+ ],
+ "content-length": [
+ 89
+ ]
+ },
+ "body": "{\"prospect\":1,\"reminder_datetime\":\"2017-12-22T18:56:00.000Z\",\"description\":\"description\"}"
+ }],
+ "type": "REQUEST_SAVE_REMINDER_FAILURE",
},
- Object {
- "data": Object {
- "payload": "payload",
- },
- "type": "RECEIVE_SAVE_REMINDER",
- },
URL似乎匹配。为什么它会说
Nock:No match for request
?谢谢 因为您不仅要匹配URL,还要使用Nock验证预期的负载。如果将nock post()调用替换为.post('api/prospect/add rementer',()=>true)
我认为时间戳的差异不会影响您