差異處
這裏顯示兩個版本的差異處。
web:reactjs:test:teststaticmethod [2019/03/10 16:25] tony [Reference] |
web:reactjs:test:teststaticmethod [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | ====== React - How to test component with static method? ====== | ||
- | ===== Problem ===== | ||
- | 在撰寫程式時,我會習慣將同性質的utility method放在同一個class中。以實作Login、Logout的功能來說,我就會建立一個class叫Auth,會包含以下methods: | ||
- | <code javascript> | ||
- | import React, { Component } from 'react'; | ||
- | |||
- | const session_token_key = 'session_token'; | ||
- | |||
- | export default class Auth extends Component { | ||
- | | ||
- | static signIn(username, password){ | ||
- | // check credential | ||
- | sessionStorage.setItem(session_token_key, 'session_info'); | ||
- | } | ||
- | |||
- | static signOut(){ | ||
- | sessionStorage.clear(); | ||
- | } | ||
- | |||
- | static checkLogin(){ | ||
- | if( !sessionStorage.getItem(session_token_key) ) { | ||
- | throw new Error("no session info"); | ||
- | } | ||
- | } | ||
- | }; | ||
- | </code> | ||
- | 而Logout的元件中,則會透過Auth.signOut去執行登出的動作: | ||
- | <code javascript> | ||
- | import React, { useContext } from 'react'; | ||
- | import Auth from './Auth' | ||
- | import { NavItem, NavLink} from 'reactstrap'; | ||
- | import { AuthContext } from './AuthContext'; | ||
- | |||
- | |||
- | function Logout(){ | ||
- | const [ authState, setAuthState ] = useContext(AuthContext); | ||
- | |||
- | const signOut = ()=>{ | ||
- | Auth.signOut(); | ||
- | setAuthState(false); | ||
- | window.location.href = '/'; | ||
- | }; | ||
- | |||
- | return ( | ||
- | <NavItem aria-label="logout-nav-item" className="d-md-down-none" onClick={signOut}> | ||
- | <NavLink href="#" ><i className="icon-logout"></i></NavLink> | ||
- | </NavItem> | ||
- | ); | ||
- | } | ||
- | |||
- | export default Logout; | ||
- | </code> | ||
- | 在先前針對[[web:reactjs:react_hook:usecontext|useContext]]的使用文章中,參考過別人使用jest mock static的寫法如下: | ||
- | <code javascript> | ||
- | const auth_do_nothing = jest.fn(); | ||
- | auth_do_nothing.mockImplementation(()=>{}); | ||
- | Auth.signOut = auth_do_nothing.bind(Auth); | ||
- | </code> | ||
- | 但這寫法存在restore的問題,會將狀態延續至下一個testcase中;因此本篇文章將分享透過[[https://sinonjs.org/releases/latest/|Sinon]]去mock static method並且清除mock狀態的做法。 | ||
- | ===== How to? ===== | ||
- | |||
- | ===== Reference ===== | ||
- | * [[https://sinonjs.org/releases/v7.2.7/stubs/|Stubs - Sinon.JS]] | ||
- | * [[https://www.robinwieruch.de/react-fetching-data/|How to fetch data in React?]] | ||