React context API

  1. Provider提供的值為準
  2. createContext 後面提供的預設值,是給上層如果沒有找對應的Providercomponent話用的。
  3. 每一個context物件都有一個ProviderReact會讓它的吸精元件訂閱這些context
  4. 需要注意reference identity,避免不必要的re-render

實際使用的教學:
今天我要寫一個🌲🐦🐦的context

1. 首先先來createContext

const TreeBirdBirdContext = React.createContext(['🌲', '🐦']);

2. 之後來做它的 Provider

const TreeBirdBridProvider = ({children}) => {
  const [state, setState] = useState(['🌲', '🐦', '🐦'])
  return (
    <TreeBirdBirdContext.Provider value={[state, setState]}>
      {children}
    </TreeBirdBirdContext.Provider>
  )
}

3. 接著是顯示畫面、操作的邏輯

const Controller = () => {
  const [state, setState] = useContext(TreeBirdBirdContext);

  const addBird = () => {
    setState(oldArray => [...oldArray, '🐦']);
  }
  return (
    <>
      <div>{state}</div>
      <button onClick={() => addBird()}>Click Me</button>
    </>
  )
}

4. 接下來把他們包起乃

const App = () => {
  return (
    <TreeBirdBridProvider>
      <Controller />
    </TreeBirdBridProvider>
  )
}
export default App;

然後就大功告成溜!

在這裡可以看

react-testing-library 學習

const Button = ({langHelper, action}) => <button type="button" onClick={action}>{langHelper('clickMe')}</button>;

test('callback is called onClick', () => {
  const langHelper = jest.fn().mockImplementation(key => key);
  const callback = jest.fn();

  render(<Button action={callback} langHelper={langHelper} />);

  // multiple ways to do the same here.
  // - since you have only a single button, cannot possible select anything else here than the one you have
  userEvent.click(screen.getByRole('button'));
  // - using the i18n translation key. since langHelper is mocked, we know that this is the key we should see
  userEvent.click(screen.getByText('clickMe'));
  // - basically the same as yours, just without regex
  userEvent.click(screen.getByRole('button', {name: 'clickMe' }));
  // - yours
  userEvent.click(screen.getByRole('button', {name: /clickMe/i}));

  expect(callback).toHaveBeenCalledTimes(1);
});

這是多語系的範例

為什麼不用Enzyme要用React Testing Library

這是Enzyme的範例

it('simulates click events', () => {
    const onButtonClick = sinon.spy();
    const wrapper = mount((
      <Foo onButtonClick={onButtonClick} />
    ));
    wrapper.find('#foo').simulate('click');
    expect(onButtonClick).to.have.property('callCount', 1);
});
  1. 這個測試需要HTML上有一個idfootag,假設id修改了,它不就爆掉了
  2. 使用者看網頁,不會看到它有一個idfoo的東西,他只會看到網頁畫面,例如一個按鈕,上面寫「如果你覺得露娜很可愛,點我」

這些文章解釋了為什麼不用Enzyme
React Testing Library: The Modern Way to Test React Components
How to use React Testing Library Tutorial

重點截取:
React beginners often confuse the tools for testing in React. React Testing Library is not an alternative to Jest, because they need each other and every one of them has a clear task.
In modern React, developers will not get around Jest for testing, because its the most popular testing framework out there for JavaScript applications.

How to use React Testing Library Tutorial

React Test

  1. Jest 會找出在__tests__ 資料夾的 js 檔。或是檔名後面是.test.js / .spec.js的檔案
  2. it()test()來寫測試,也可以用describe()來包住這些測試,不過不是必要的
  3. describe()的description可以是React的component名稱(good practice)
  4. it()的description通常是present-tense verb
  5. 因為是走TDD的BDD風格,所以都用it()
  6. 要知道什麼樣的測試範例是差的,什麼樣的測試是好的(看書、看文章可能會看到範例,要能分辨這直接搬來用好不好)
  7. 要知道該寫什麼樣的測試,例如「直接測一個function有沒有被執行」是bad practice
  8. 要知道不要寫implemention details(實作細節)。要從使用者操作的角度來寫測試。
  9. 想要讓jest一直監測測試檔案的話,要把package.json的指令改成jest --watchAll
  10. 要知道what should be tested(什麼樣的情況該寫個測試), how to write (熟悉語法到能寫要測的那一段)
  11. npm t指令、npm run testnpm test都可以開測

參考:
https://create-react-app.dev/docs/running-tests

不錯的影片,實際講了該寫怎麼樣的測試。

寫前端測試

前端測試的類型有:

  • Unit testing
  • Visual regression testing
  • Acceptance Testing
  • End to End Testing ( functional testing )
  • Snapshot Testing

不錯的工具:
jest-runner-groups
關注的工具:
cypress-react-unit-test

挑選工具:
https://react-hooks-testing-library.com/

參考文章:

Testing Overview
An introduction to frontend testing
What is Acceptance Testing? | Agile Alliance

What Is Defect Clustering and How Do You Defeat It?
解釋何為”Defect Clustering”
30天快速上手TDD

Fullstack React: Introduction to Testing
Visual Regression Testing is Stupid

TOP VISUAL REGRESSION TESTING TOOLS
Front End Testing: A Complete Conceptual Overview

Automated Frontend Testing

Common mistakes with React Testing Library

Testing Your Frontend Code: Part IV (Integration Testing)

Static vs Unit vs Integration vs E2E Testing for Frontend Apps

How They Test