Sto provando a testare una chiamata API in un'app redux. Il codice più o meno segue il modello delineato nel Async Creatori di azione sezione dei documenti Redux:Nock non sta intercettando la chiamata API nel test Redux
http://redux.js.org/docs/recipes/WritingTests.html
l'essenza di esso è che si utilizza Redux-finto-store per registrare e far valere nei confronti qualsiasi azione che viene attivata.
Questa è l'intera prova, utilizzando la cocca per deridere la chiamata API:
import React from 'React'
import ReactDOM from 'react-dom'
import expect from 'expect';
import expectJSX from 'expect-jsx';
import TestUtils from 'react-addons-test-utils'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import nock from 'nock'
expect.extend(expectJSX);
import * as types from '../../constants/Actions'
describe('Async Search Actions',() => {
const thunkMiddleware = [ thunk ];
/* use redux-mock-store here */
const mockStore = configureMockStore(thunkMiddleware);
describe('The fetchArtistData action creator should',() => {
afterEach(() => {
nock.cleanAll()
})
it('Should fire off a ARTIST action when fetch is done', (done) => {
nock('http://ws.audioscrobbler.com')
.get('/2.0/')
.query({method: 'artist.search', artist: 'ho', api_key: 'abc123', format: 'json', limit: 5})
.reply(200,
{
fake: true
}
)
const expectedActions = [
{ type: types.ARTIST, artists: {
fake: true
}
}
];
let store = mockStore([], expectedActions, done);
store.dispatch(fetchArtist('ho'))
});
});
});
Ma sembra che il vero api LastFM viene chiamato quando viene eseguito il test ... dati reali viene restituito da LastFM piuttosto rispetto alla risposta falsa cocca.
Questa è l'azione creatrice stessa:
export function fetchArtist(search) {
return dispatch => {
return fetch(`http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=${search}&api_key=abc123&format=json&limit=5`)
.then(handleErrors)
.then(response => response.json())
.then(json => { dispatch(ArtistData(searchTerm, json)) })
.catch(handleServerErrors)
}
}
L'asserzione non riesce perché la risposta in diretta lastFM non è la stessa come la risposta mi aspetto come per l'oggetto expectedActions
..
I' ve provato assegnando la cocca a una variabile e di accedervi out.The registro mostra questo:
Nock sembra essere l'aggiunta porta 80 al uRL, non so se questo causa l'API effettivo non beffeggiare:
keyedInterceptors: Object{GET http://ws.audioscrobbler.com:80/2.0/?
method=artist.search&artist=john&api_key=abc123&format=json&limit=5
Qualche idea cosa c'è che non va qui?
Stai usando questo nodo o la browser? Non credo che nock funzioni nei browser, solo il nodo –
Ah ok, questo è il problema allora, sto eseguendo i test su PhantomJs –
Sembra che nock non ami il recupero del browser https://github.com/node-nock/Nockberge/temi/409. Andando a provare e passare a fetch-mock come suggerito per il momento –