- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 340字
- 2021-08-13 15:12:56
Snapshot testing expandable components
This time, we will demonstrate a tricky part of snapshot testing.
Let's start by creating our first snapshot test. Go to Chapter_1/Example 4_Stateful_expandable_component and run yarn test in the command line. You should see that one test passes. What kind of test is it? It's a trivial unit test that's located in the App.test.js file.
It's time to create our first snapshot test. Replace expect(rendered).toBeTruthy(); with expect(rendered).toMatchSnapshot();. It should look like this:
it('renders', () => {
const rendered = renderer.create(<App />).toJSON();
expect(rendered).toMatchSnapshot();
});
Once you have this, rerun yarn test. A new directory called __snapshots__ should be created with the App.test.js.snap file inside it. Take a look at its contents. This is your first snapshot.
It's time to test the app's coverage. You can do this with the following command:
yarn test -- --coverage
It yields something a little concerning:
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
All files| 66.67 | 50 | 50 | 66.67
App.js | 66.67 | 50 | 50 | 66.67 | 18,23,26
We have one component that has one branch (if), and after performing a snapshot test, the coverage is not even near 100%. What's wrong?
There is obviously a problem with the branch that relies on state, but would it account for over 30% of the lines? Let's see the full report. Open the ./coverage/lcov-report/App.js.html file:
Now, you see what is wrong. The answer is pretty simple—snapshot tests do not test prop functions. Why? First of all, this does not make much sense. Why would we convert a function to JSON, and how would it help? Secondly, tell me how to serialize the function. Shall I return function code as text or compute output in some other way?
Take this example as a lesson that snapshot tests are not enough.
- C++ Builder 6.0下OpenGL編程技術(shù)
- Unity 2020 Mobile Game Development
- PostgreSQL 11從入門到精通(視頻教學(xué)版)
- Java設(shè)計(jì)模式及實(shí)踐
- C語言開發(fā)基礎(chǔ)教程(Dev-C++)(第2版)
- Go語言精進(jìn)之路:從新手到高手的編程思想、方法和技巧(2)
- 深入理解C指針
- OpenCV with Python By Example
- Mastering Elasticsearch(Second Edition)
- 深入理解BootLoader
- Mudbox 2013 Cookbook
- H5+移動(dòng)營銷設(shè)計(jì)寶典
- Effective C++:改善程序與設(shè)計(jì)的55個(gè)具體做法(第三版)中文版(雙色)
- Flutter之旅
- Spring Boot 2+Thymeleaf企業(yè)應(yīng)用實(shí)戰(zhàn)