2017-08-15 134 views
8

我正在学习如何测试和使用一些示例作为指南我试图模拟登录帖子。这个例子使用了对http调用的获取,但是我使用了axios。这是我得到如何测试react-saga axios post

超时错误 - 异步回调不被jasmine.DEFAULT_TIMEOUT_INTERVAL

所有的答案,这个错误的指定的超时时间内调用了同取,我该怎么办办这与爱可信

./saga

const encoder = credentials => Object.keys(credentials).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(credentials[key])}`).join('&') 

const postLogin = credentials => { 
    credentials.grant_type = 'password' 
    const payload = { 
    method: 'post', 
    headers: config.LOGIN_HEADERS, 
    data: encoder(credentials), 
    url: `${config.IDENTITY_URL}/Token` 
    } 
    return axios(payload) 
} 

function * loginRequest (action) { 
    try { 
    const res = yield call(postLogin, action.credentials) 
    utils.storeSessionData(res.data) 
    yield put({ type: types.LOGIN_SUCCESS, data: res.data }) 
    } catch (err) { 
    yield put({ type: types.LOGIN_FAILURE, err }) 
    } 
} 

function * loginSaga() { 
    yield takeLatest(types.LOGIN_REQUEST, loginRequest) 
} 

export default loginSaga 

./login-test

const loginReply = { 
    isAuthenticating: false, 
    isAuthenticated: true, 
    email: '[email protected]', 
    token: 'access-token', 
    userId: '1234F56', 
    name: 'Jane Doe', 
    title: 'Tester', 
    phoneNumber: '123-456-7890', 
    picture: 'pic-url', 
    marketIds: [1, 2, 3] 
} 

describe('login-saga',() => { 
    it('login identity user', async (done) => { 
    // Setup Nock 
    nock(config.IDENTITY_URL) 
     .post('/Token', { userName: '[email protected]', password: 'xxxxx' }) 
     .reply(200, loginReply) 

    // Start up the saga tester 
    const sagaTester = new SagaTester({}) 

    sagaTester.start(loginSaga) 

    // Dispatch the event to start the saga 
    sagaTester.dispatch({type: types.LOGIN_REQUEST}) 

    // Hook into the success action 
    await sagaTester.waitFor(types.LOGIN_SUCCESS) 

    // Check the resulting action 
    expect(sagaTester.getLatestCalledAction()).to.deep.equal({ 
     type: types.LOGIN_SUCCESS, 
     payload: loginReply 
    }) 
    }) 
}) 
+0

你是怎么做发电机的工作? – JoseAPL

+0

第一次使用它们,所以仍然在学习 – texas697

回答

1

您收到以下错误:Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL,因为您没有在测试中调用done回调。

+0

你能说明你的意思吗? – texas697

+0

刚刚添加了这个setTimeout(()=> done(),200) – texas697

+0

这个答案是否解决了这个问题?它不清楚你应该叫做完成()。以这种方式调用可能会过早地返回done()。 – 82Tuskers

1

由于您为nock嘲讽有specified a body{ userName: '[email protected]', password: 'xxxxx' }),它不会响应loginReply,直到它变得既给定的URL和身体POST请求。但是,您不会发送credentials与您的LOGIN_REQUEST操作,因此您的axios请求主体(payload.data)始终为空。这就是为什么你的nock模拟不会在指定的异步超时内回复,并且jest会给出此超时错误。

为了解决这个问题,你要么必须删除指定的身体在你的nock设置或派遣LOGIN_REQUEST行动凭据和更改指定的身体,以配合您设置为​​编码凭据。

+0

我从nock中删除了凭据但仍然出现相同的错误 – texas697