By Developers, For Developers

Historical errata for Test-Driven React

PDF PgPaper PgTypeDescriptionFixed onComments
139ERROR

After adding ’ecmaFeatures: { jsx: true, }, to the root .eslintrc.js file, the book indicates there will be no output from linting.

When I run lint at this point the error changes from:
> eslint “src/tests/hello.test.js”

/Users/robie/mycode/test-drive-react/test-driven-carousel/src/tests/hello.test.js
6:5 error Parsing error: Unexpected token <

to:
> eslint “src/tests/hello.test.js”

/Users/robie/mycode/test-drive-react/test-driven-carousel/src/tests/hello.test.js
6:21 error Parsing error: Unexpected token /

The change in error indicates that JSX may be recognized due to the change, but lint is still puking on the slash in the closing

tag.

I am diffing my code (which is very similar if not identical to the book) against the code download.
I notice the book code includes
//.eslintrc.js

parser: ‘babel-eslint’,

That was one of the possible fixes that the Internet suggests.

I also note that all of the paserOptions are omitted from the downloaded code.

It seems like the steps for installing babel-eslint may have been omitted from the text in the book.

2019-03-31Hi Robie, \n \nI've learned that this problem is caused by an indirect dependency conflict. If you delete your `node_modules `dir and `package-lock.json`, then install your dependency tree from scratch with `npm install`, the issue should go away.
13SUGGEST

Just a minor thing: in every other TDD resource I’ve read, the mantra is the “Red, Green, Refactor” cycle, the “cycle” part providing the Repeat element.

Thanks for writing the book BTW. One of the really big annoyances I’ve found with React is that automated testing seems to have been an afterthought. Most people seem to develop using the old “write a bit, manually test a bit” cycle, and not doing any automated tests at all.

2019-01-21Hi Richard, \n \nI decided not to introduce the concept of refactoring in the first chapter, which is why the mantra is a little different. Chapter 5 (coming in the next beta) will be focused on refactoring. Thank you for your feedback!
102TYPO

npm install —save-dev style-lint@9.9.0
should be
npm install —save-dev stylelint@9.9.0

2019-01-21
109ERROR

In ‘allows styles to be overridden’ test case, styled is used without importing it.

import styled from ‘styled-components’ within CarouselSlide.test.js fixes it.

2019-01-21
56ERROR

When I get to

One more attempt:
$ npm run lint src/tests/hello.test.js
No news from ESLint is good news!

I actually get

5:17 error Parsing error: Unexpected token /
related to this line

Hello, JSX!

;

2019-03-31Hi Philip, \n \nI've learned that this problem is caused by an indirect dependency conflict. If you delete your `node_modules `dir and `package-lock.json`, then install your dependency tree from scratch with `npm install`, the issue should go away.
61TYPO

On pages 61and 63 the text talks about passing props through to a div. I found that confusing because in the code the props are being passed through to a button

2019-01-21
91ERROR

In the chapter related to Packaging an App with Webpack • 91
after running npm run build the following compilation error is displayed and the index.html build is not correct.

ERROR in Error: Child compilation failed:
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: …/Projects/test-driven-carousel/node_modules/html-webpack-plugin/default_index.ejs: Unexpected token (1:0)

2019-03-31Hi Ana, \n \nSomeone else on the errata forum reported that they had the same issue due to misreading some code in the Webpack config. The regex should be \n \n/\\.js$/ \n \nbut can be misread as \n \n/|.js$/ \n \ndue to the font used for code in the book. Sorry about that!
16ERROR

“To open the Command Palette, type Command-P (macOS)”
make that Command-Shift-P. Command-P is “Go to File”.

2019-01-21
58TYPO

“carousel” misspelled as “carousal”

2019-01-21
54SUGGEST

“Confirm that npm run test continues to yield the same result after making the dependency change.”

I didn’t understand this sentence. What dependency change?

2019-01-21
56ERROR

After adding ````ecmaFeatures: { jsx: true, },` to .eslintrc.js, I still received a parser error “Unexpected token /”. To resolve this, I had to add the babel-eslint parser at this point. The book has one install this later in the chapter but perhaps that should be moved up to here.

2019-03-31Hi Charles, \n \nI've learned that this problem is caused by an indirect dependency conflict. If you delete your `node_modules `dir and `package-lock.json`, then install your dependency tree from scratch with `npm install`, the issue should go away.
66SUGGEST

After adding Jest setup files, if you have jest running with —watchAll, it will begin to error at this point. Would be helpful to mention that in this instance, one will need to restart Jest to load the setup.

2019-01-21
70ERROR

"In short: We should pass every prop except the three we’re explicitly using through to the

."

The changes made in the implementation after this pass the props to the

, not the

. This error is also present in the test description in the listing on page 71 and subsequent listings of the same file.

2019-01-21
80SUGGEST

We just added three new tests without doing any work on the implementation. Ideally in TDD, one test is added, then implemented, at a time; in this instance, I think the “Next” and “Previous” button tests here and earlier (p76) are related enough and similar enough that it’s acceptable to add them together, but the ‘renders the current slide as a CarouselSlide’ test is not so closely related to the other two being added on p80. I would suggest writing the ‘renders’ test first, getting it passing, then in another step adding the tests for the wrapping-around of the slideIndex.

2019-01-21Thank you, this is an excellent suggestion.
82TYPO

“One last thing: We need to declare propTypes in order to make the linter happy. This time, use the static keyword to declare them as a static property within the class definition:”

The code being added in the following listing was already present in the previous listing on p81.

2019-01-21
93ERROR

“With that, the example should be ready to view in the browser. Refresh the page:”

Refreshing the page will not show the changes just made on p92 unless npm run build is done first.

2019-01-21
95TYPO

Missing word: “Worse, removing style rules becomes a dangerous.”

2019-01-21
96TYPO

in this and subsequent listings, “PropTypes” is imported with the first letter capitalized; in previous listings it was imported as “propTypes”.

2019-01-21
98TYPO

“If, for example, we’d named the prop height inside of imgHeight, then it would have been passed down as the height DOM attribute of the .”

I think you may have meant “instead” here instead of “inside”.

2019-01-21
114ERROR

“Pruning them yields the final CarouselSlide.test.js for this chapter:”

Not sure what happened but after following this step, the snapshot tests failed for me. running with the -u option as described later cleared this up but I don’t understand exactly why the rendered DOM no longer matched the snapshots at this point.

2019-03-31Hmm, I don't believe that removing other tests would affect the snapshot. If you can recreate the project at this point and replicate this bug, shoot me an email: trevorburnham@gmail.com
91SUGGEST

Regarding Ana’s reported problem (#84230). I had the exact same thing, and was trying to install ejs-loader and what not, until I figured out I had misread the code on PDF page 87.

The regex at rules: test looks like it is containing a pipe symbol - /|.js$/ but it actually is a backslash to escape the point - /\\.js$

2019-01-21Thank you, this is very helpful. I'll relay the report about the code typography to the folks at PragProg.
43SUGGEST

In your solution for the palindromes project (chapter 2), all your test cases are on strings that are complete palindromes, rather than text containing palindromes, e.g. “WoW” vs “The WoW Factor”. The code to satisfy the former is a lot simpler than your more rigorous solution, and TDD usually requires writing the simplest code to make the tests pass. :-)

Put another way, you should have at least one test case on a string that contains a palindrome, e.g. “The WoW factor”.

For what it’s worth, my lazy dev solution was:

module.exports = (str) => {
const forward =
str
.replace(/\\W/g, ’’)
.toLowerCase();

const reversed =
forward
.split(’‘)
.reverse()
.join(’’);

if (reversed === forward)
return [reversed];

return [];
};

Cheers,
Richard

2019-01-23Thanks, I'll consider that!
79ERROR

(i.e. a technical error in the generation of the PDF document, not the content of the text itself.)

Minor annoyance for anyone trying to save themselves some typing when following along with the code examples…

Copy/pasting the code sample on page 79 is a bit iffy. E.g. try highlighting the declaration:

const slides = [
{
imgUrl: …etc…
:
:
};

The literal for the first slide in the const declaration gets highlighted okay, but the second and third do not. Pasting the code sample into an editor leaves the latter two “slides” empty.

Cheers,
Richard

2019-04-04Trevor Burnham says: Thanks for reporting these PDF bugs! I'm seeing the same issues. I've passed the bug report along to the folks at PragProg.
87ERROR

Like #84356, a technical error in the PDF: when copy/pasting code sample for webpack.config.js, a lot of the non-code text after it gets selected as well.

2019-04-04Thanks for reporting these PDF bugs! I can confirm that I'm seeing the same issues. I've passed the report on to the folks at PragProg.
87SUGGEST

Minor inconsistency in “entry” section of webpack.config.js, between the version on page 87 and that on page 90.

On page 87, the entry point is labelled “component”, while on page 90 it’s called “carousel”. Probably better to call it “carousel” in both places, and also adjust corresponding note (2) on page 87 to refer to it as such.

2019-02-03
91ERROR

Another technical copy/paste error in the PDF. Copying the code for slides.js on pp91-92, the code for the last slide (p92) doesn’t get selected for copy.

2019-04-04Thanks for reporting these PDF bugs! I'm seeing the same issues. I've passed the bug report along to the folks at PragProg.
121TYPO

Unit test code sample begins with:

// src/tests/HasIndex.js

I think this (and more importantly, the file name it indicates) should be:

// src/tests/HasIndex.test.js

for the testing framework to recognise it as a unit test script.

2019-02-14
62TYPO

“And since we can reasonably expect every —>slide<— to have children…” should read “button” instead of “slide”.

2019-03-02
71TYPO

"it(’passes other props through to the —>

<—" should read "

" instead of "

"

2019-03-02
130SUGGEST

I think that in Chapter 5 you’ve started drifting away from the essence of TDD, by which I mean:

1. Write a failing test
2. Write the smallest amount of code to make that test pass
3. Refactor if required, and repeat the cycle.

Adding multiple tests at once and then updating the application code also makes it more difficult to follow.

Case in point: the test code on p130 has four new tests added in the middle of the existing tests, making it harder to determine what’s new. I have to carefully examine the existing tests to see if they’ve changed, or copy/paste the lot into my editor if I’m lazy - this also copies the annotation markers, along with copy/paste issues I’ve noted in previous submissions.

Plus I have to scroll to the next page to read the explanations for each new test. Easier on hard copy if those are facing pages, but harder on PDF.

Also, the third new test (“allows `index` state to change if the `index` prop is unset”…) is not a failing test. It passes before I’ve made any changes to the application code.

In summary, please consider doing just one test at a time.

2019-03-31This is a good point. I'll try to split things up more before the final release.
133ERROR

When adding the test, ‘allows `slideIndex` to be controlled’, to Carousel.test.js, you also need to import mount from enzyme.

Also, when I run this particular test, React 16.7.0 shows the following warning:

console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: React does not recognize the `defaultSlideIndex` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `defaultslideindex` instead. If you accidentally passed it from a parent component, remove it from the DOM element.
in div (created by Carousel)
in Carousel (created by HasIndex(Carousel))
in HasIndex(Carousel) (created by WrapperComponent)
in WrapperComponent

2019-03-17
135SUGGEST

Following on from my comments on p133 on illustrating the practice of TDD, I’ll just note that in AutoAdvances.test.js, the following tests are green before any code has been written to make them pass:

- “has the expected displayName”

- “does not set a timer if `autoAdvanceDelay` is null”
- “clears the timer on unmount”

2019-04-04That's true. I'm not sure how you'd start with a failing test in the case where you're trying to prove a negative (e.g. the timer isn't set). If you have any suggestions, shoot me an email: trevorburnham@gmail.com
135ERROR

Correction to my other comment on the page: I meant to refer to my comment for p130, about TDD.

Also, for the test, “does not set a timer if `autoAdvanceDelay` is null”, React 16.7.0 raises the following warning:

console.error node_modules/prop-types/checkPropTypes.js:19
Warning: Failed prop type: The prop `autoAdvanceDelay` is marked as required in `AutoAdvances(MockComponent)`, but its value is `null`.
in AutoAdvances(MockComponent)

so ComponentWithAutoAdvance’s autoAdvanceDelay prop needn’t be “isRequired”.

2019-03-19
149SUGGEST

At risk of seeming to dumb things down too much, it might be worth explicitly pointing out that in the Travis CI badge code in README.md, one should replace “username” with one’s Github username.

As a first time Travis user, I got caught by this when I just copy/pasted the code, and was briefly confused when my project build status was shown as “unknown”. :-)

2019-03-17
89TYPO

There’s some confusion on “component” vs “carousel” in the webpack config. webpack entry is “carousel: ‘./src/Carousel.js’”, however it looks like you might mean that to be “component: ‘./src/Carousel.js’”. The notes on this code specify, “Here we’re telling Webpack to build a bundle called component.js that contains src/Carousel.js and its dependencies.” Further on, there are other references to “component”, although there are also other references to “carousel”.

2019-03-02
90ERROR

On this page, the book says “npm run lint”, which then appears to translate to “eslint .”, but unless I missed something, this isn’t how the command is configured. The command is configured to simply be “eslint”, requiring one to pass the file(s) with the command when running “npm run lint”. Running “npm run lint” as-is results in “eslint [options] file.js [file.js] [dir]” followed by the documentation for how to use the command.

2019-03-02
92TYPO

“Since the example code imports the Carousel component, Carousel and all of its dependencies—including React—-are in both bundles.” At this point, example.js does not yet import Carousel.

2019-03-02
153ERROR

I think that the pre-commit section is missing the word, “run”, before “format”, i.e. should read:

“pre-commit”: “npm run lint && npm run format”

2019-03-17
060SUGGEST

Thank you for this book.

For me, the book doesn’t start until page 60. There is some motivational / philosophy type stuff in the introduction, but the rest is just dev-env setup and npm wrangling. Same with git. Git commit habits are orthogonal to the book topic.

Another PP book that I really liked was Venkat Subramaniam’s Test-Driving JavaScript Applications. That book assumes use of the code download, provides working package.json and etc. configuration files, and uses the text only to explain what is configured and why.

2019-04-04Thank you for your feedback. It's true that this book spends a lot of time on dev env setup and workflow. This was a conscious choice, but I know it may cut against expectations for a book with this title. I hope you got something out of the book nonetheless!
81ERROR

Thank you for this book. This chapter 3 has been especially helpful.

On p.81, the section “Manipulating State in Tests” begins using a state variable called “slides”. Somehow I missed the part where passing through slides props was set up. Searching, I’m pretty sure it isn’t present. However, I might have missed it.

Thank you again for this helpful guide.

2019-03-17
46ERROR

expect(findLongestPalindrome(‘bananarama’)).toBe(null);

This will return [‘anana’] and not null.

2019-03-17The palindromes() function would do that, but findLongestPalindrome() is defined here as a helper function that works from the start of the given string. Sorry for the confusion—I realize that the helper function name is misleading. I'll rename it.
87TYPO

Towards the bottom of the page there are two consecutive notes that are labelled “1”. The first one makes sense as it describes the code block immediately above it. The second note doesn’t seem to correspond to the above block.

2019-05-07
182TYPO

“value” is misspelled in test
it(‘wraps slideIndex to the min vaue when Next is clicked’)

2019-05-07
86TYPO

“value” is misspelled in test
it(‘wraps slideIndex to the min vaue when Next is clicked’)

2019-05-07
41SUGGEST

I had to create “.eslintignore” and add “coverage/” to it in order to get “npm run lint” to run without failures.

2019-05-07
128ERROR

When I use the example code from pg 128 for src/HasIndex, the given test case code produces two failures of " ReferenceError: index is not defined" on lines 25 and 35.

I believe you want something like “const index = this.state.index;” in both the handleIncrement and handleDecrement functions. That change at least makes the tests pass :)

I’m pretty new to React so could be a better solution, but I’ve tried several times and get the same issue with the code from Ch4 plus the test and implementation code in Ch5.

2019-05-07
1SUGGEST

I was a little surprised there wasn’t a chapter on testing redux. I guess the higher order chapter heads that way, but I sort of expected to learn how to test redux as well.

I’m glad there’s a Ch6 on CI and husky is great, but CI in particular is pretty straightforward and could have moved to an appendix or a bonus chapter. Redux seems to be pretty important in the React world and worth a quick example, though I’m not 100% sure how that would flow smoothly from your carousel example

2019-05-07Thanks for your feedback! It's a little late to add new content to the book, but I'll consider adding Redux in a future edition.
58SUGGEST

I don’t think this is really an error in the book - likely more of a bug somewhere in the NPM ecosystem (I’m on npm -v = 6.9.0, but not sure if that’s relevant).

In going through Chapter 3 (in particular the initial eslint setup), I ran into an issue where after adding ecmaFeatures: {jsx: true}, I got a different parsing error (“Unexpected token /” - about the JSX closing tag). After some digging, I found that by deleting both node_modules and package-lock.json (just the first was insufficient), an npm install would get me working code.

It basically seems to be the issue described here: GITHUB DOT COM /styleguidist/react-styleguidist/issues/1321#issuecomment-494732909 (sorry, no urls allowed in this form I guess…)

And I’ll also give you a gist of the package-lock.json diff I got, in case it helps: GIST DOT GITHUB DOT COM /trptcolin/2b7770de710e751a5f2ff4cba71d0e4a

I probably won’t drill any deeper on this since I’m totally unblocked now, but I did want to give you a heads up, in case there’s a way to avoid frustration for other folks. For what it’s worth, the place I needed to do this was after installing the ESLint stuff (doing it earlier in the process didn’t help).

2019-11-28
85SUGGEST

It looks like the React folks are now going as far as actively to recommend using react-testing-library instead of enzyme. For example: reactjs dot org/docs/test-utils.html "We recommend using react-testing-library which is designed to enable and encourage writing tests that use your components as the end users do.

Alternatively, Airbnb has released a testing utility called Enzyme, which makes it easy to assert, manipulate, and traverse your React Components’ output."

I’m loath to go against a recommendation like that as I know that later I’ll run into trouble if I don’t (e.g. “I see you’re using Enzyme. We’re using RTL and aren’t seeing that problem…”). Unfortunately, this now means that as I’m going through the book, I’ll have to change the examples in Enzyme to make them work as RTL-related code.

I wonder if it would be helpful to include as an Appendix some samples where you rewrite some of the earlier code examples that used Enzyme and show how they would be done in RTL. I presume it would only take a few code samples, but I’m sure it would be valuable.

2019-06-05I talk a little bit in the book about react-testing-library. It implies a different testing methodology, with some pros and cons vs. Enzyme. Enzyme remains very popular and I don't think it's going to disappear any time soon. Even if you wind up using react-testing-library, I think you'll feel like the time you spent learning Enzyme was time well spent! It'll give you a different view of how React testing can be done.
58SUGGEST

I had the same issue as Colin Jones, eslint was reporting an error on JSX closing tags. Did as suggested, deleted node_modules and package-lock.
Started to work again, but VS Code started sending an error about eslint couldnt find eslint-plugin-jest/index.js
Had to close vs code and error fixed.

2019-11-28
156ERROR

Using storybook/addon-actions4.1.11 breaks storybook ( a blank page is shown when running “npm run storybook”). Upgrading to version 5.1.9 fixes the issue. Seems like the addons need to have the same major version as storybook itself (see github issues of storybook.js)

120108ERROR

I have progressed to this point within the book (the beginning of ‘Testing Styled Components’). At the beginning of that chapter, it tells me I should expect a certain output from my tests.

However, the styled-component is not being read correctly by jest. It is receiving the JSON of the styled component instead of the html output.

● CarouselSlide › renders an and a

as children

expect(received).toBe(expected) // Object.is equality

Expected: “img”
Received: {“$$typeof”: Symbol(react.forward_ref), “attrs”: [], “componentStyle”: {“componentId”: “CarouselSlide_Img-ds4ujd-0“, ”isStatic“: false, ”rules“: [”object-fit:cover;width:100%;height:“, [Function anonymous], ”;“]}, ”displayName“: ”CarouselSlideImg“, ”render“: [Function anonymous], ”styledComponentId“: ”CarouselSlide_Img-ds4ujd-0”, “target”: “img”, “toString”: [Function anonymous], “warnTooManyClasses”: [Function anonymous], “withComponent”: [Function withComponent]}

Additional info:
- package.json is the same as the book code for that chapter
- The styled component is being read correctly by the browser (as per the figure on P105)
- I am using VSCode as per the instructions in the book
- I cant verify the tests are correct since the book code changes further into the chapter
So I think there may be some problem with a plugin or similar

Any feedback or otherwise would be greatly appreciated.

thank you, take care

353ERROR

When I installed storybook/addon-actions4.1.11 and storybook/addon-knobs4.1.11 as instructed on pages 353 and 355 (in the epub version) in the “Enhancing Stories with Addons” section of chapter 6, the “Actions” and “Knobs” tabs do not display, and I get a few errors in the browser console (in Chrome). The errors/warnings are:

> (Error) Uncaught TypeError: (0 , _core.withCSSContext) is not a function
>
> (Warning) Events.REGISTER_SUBSCRIPTION is deprecated and will be removed in 6.0. Please use useEffect from @storybook/client-api instead.
>
> (Error) Warning: Unknown event handler property `onIndexChange`. It will be ignored.

To fix this issue, I deleted those two packages from package.json, removed my node_modules directory, ran ‘npm install’ and then reinstalled the latest versions of these two packages with:

npm i -D storybook/addon-actions5.3.12
npm i -D storybook/addon-knobs5.3.12

342TYPO

The sentence:

“Then create a REACT.md project in the root of your test-driven-carousel project.”

should be

“Then create a README.md file in the root of your test-driven-carousel project.”

39ERROR

It seems that the VS Code setting for prettier extension that does the ESLint integration has been deprecated. Instead the plugin suggests integration using “codeActionsOnSave” see prettier vscode github and then the heading “linter-integration” . This doesn’t affect the formatting though (e.g. adding the configuration format on save as suggested on page 40 undoes the ESLint benefit?), which will still not integrate with Prettier .. so I’m not sure what the work around for that would be.

39ERROR

Prettier has been updated since this was published.

In the “Integrating Prettier with VS Code” section on pg39,
when you add the following to user settings:

“prettier.eslintIntegration”: true,

VS Code will indicate that the setting has been deprecated,
instructing you to use ‘prettier-eslint’ instead of ‘prettier’
and directing you to github.com/prettier/prettier-vscode#linter-integration

This page then has some suggested settings as well as links to further
information. After trying the suggested settings without any success
I looked at the links and tried several solutions.

I don’t know if this is the best (or even correct) way to get
ESLint, Prettier and VS Code working together but it is effective:

1. Edit User Setting and remove: “prettier.eslintIntegration”: true,
2. Run: npm install —save-dev eslint-config-prettier eslint-plugin-prettier
3. Edit .eslintrc.js in project root:
3.1 Change extends to: [“eslint:recommended”, “plugin:prettier/recommended”],
3.2 Remove:
rules: {
quotes: [‘error’, ‘single’, { avoidEscape: true }],
‘comma-dangle’: [‘error’, ‘always-multiline’],
},
4. Add .prettierrc.js to project root:
4.1 Set contents to:
module.exports = {
trailingComma: ‘es5’,
tabWidth: 2,
semi: true,
singleQuote: true,
};

78SUGGEST

A quick note might be helpful for people using wallaby. After you finish installing plugin-proposal-class-properties is, you will need to restart wallaby to remove the errors you see in the Wallaby.js Test output, and the ‘slideIndex’ test to pass.

Categories: