Test dell'app React con problemi di scherzo e token enzimatico
Ho un'app React in cui ho aggiunto unit test, ma uno dei miei test fallisce,
Ecco il mio file di prova, voglio testare i creatori di azioni getUser.
Quando corro npm testricevo il seguente errore,
FAIL UnitTests resources/js/tests/actions/index.test.js
● Test suite failed to run
TypeError: Cannot read property 'getAttribute' of null
8 | 'Accept': 'application/json',
9 | 'Content-Type': 'application/json',
> 10 | 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
| ^
11 | },
12 | });
13 |
at Object.<anonymous> (utils/api.js:10:19)
at Object.<anonymous> (store/actions/userActions.js:2:1)
at Object.<anonymous> (store/actions/index.js:2:1)
at Object.<anonymous> (tests/actions/index.test.js:3:1)
Cosa devo fare per risolvere questo problema? qualsiasi idea o soluzione sarà apprezzata.
Risposte
Bene, la versione breve è - non hai un elemento DOM che usi nel tuo file - hai due opzioni: il document.querySelectormetodo di derisione , in modo che restituisca l'oggetto con il getAttributemetodo, o la creazione di un elemento manualmente in jest-dom, come:
let metaElement;
beforeAll(() => {
metaElement = document.createElement("meta");
metaElement.name = "csrf-token";
metaElement.content = "test-token";
document.head.append(metaElement);
})
afterAll(() => {
metaElement.remove();
});
Non so, tuttavia, sia il codice del file che stai testando, sia la libreria beffarda che usi ( moxios) :)
Ottieni l'errore Cannot read property 'getAttribute' of null, il che significa che document.querySelector('meta[name="csrf-token"]')sono tornati null.
Per cambiarlo hai due opzioni :
- Modifica il documento secondo la risposta di Emazaw
O
- Utilizzare
jest.spyOnper spiaredocument.querySelectorper modificare il suo comportamento
// this should be called before attempting to read the meta's attribute
jest.spyOn(document, 'querySelector').mockReturnValue({
getAttribute: jest.fn().mockReturnValue('MOCK-CSRF-TOKEN-VALUE')
})