Hello!
I’m not sure if I’m missing something obvious, but when I try to run “npm test” I get an error saying “Cannot use import statement outside a module” and points to my component importing React. How am I supposed to solve this?
My github repo is GitHub - KBerliner/jammming: Jamming is a UI design project built with the Spotify API to allow a user to search songs, create a playlist, and add that playlist to their Spotify account..
And here is my code:
const React = require('react');
const { render } = require('@testing-library/react');
const assert = require('assert');
const Playlist = require('../src/components/Playlist/Playlist')
describe('Playlist Component', () => {
let result, component;
describe('empty playlist function',() => {
it('should render the correct text', () => {
// Setup
component = render(React.createElement(Playlist, { tracklist: [] }));
let expected = 'Start Adding Songs!';
// Exercise
result = component.container.querySelector('h4').innerHTML;
// Verify
assert.strictEqual(result, expected);
// Teardown
component.unmount();
})
})
})
1 Like
Did you ever find a solution to that? I ran into the same problem.
Thank you for sharing your Github repo. Skimming some of the tests has helped me feel re-energized after four days of breaking my brain trying to write meaningful tests that actually work for this project.
I actually just ended up using Jest since I was having that problem. Even though they don’t have that course until after and it looks like Mocha is what should be used, it was just easier for me to learn and use Jest. I used just about all the same code, you can still use describe
and it
blocks and use the Setup, Exercise, Verify, and Teardown stages (Jest automatically unmounts components so you probably won’t have to use the Teardown stage). The only differences I found were putting the tests in a folder in the src folder called __tests__
. I then left the npm test
script to run react-scripts test
.
For imports, you have to use import { render } from '@testing-library/react';
Then import your component as usual. Then to render the component use something like const component = render(<App />);
However, it might be easier to use object destructuring, for example: const { getByTestId } = render(<App />);
If you’d like, the whole format is still up on that public repo on the original post, and you can go check it out there!
1 Like