chuyin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    8
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 使用 Mock 撰寫測試(jest.fn, spyOn) 當在撰寫測試,希望專注在撰寫的測試本身(SUT),而不關注該測試的其他依賴函式或套件(DOC)時,就可以透過 Mock 來幫忙實現! - [jest.fn():](https://hackmd.io/HPKnMQMtTs292NULu76JDQ#jestfn) - 模擬一個函式 - 模擬函式回傳的其他方法 - 模擬依賴函式或套件 - [spyOn():](https://hackmd.io/HPKnMQMtTs292NULu76JDQ#spyOn) - 模擬一個函式 - 需帶入兩個參數 ```jsx! jest.spyOn(object, methodName) // 物件名稱, 物件內的方法名稱 ``` -- 👉 jest.fn() 與 spyOn() 的差異: jest.fn() 並不會實際去執行被 mock 的函式,而 spyOn 會去執行傳入的函式。** --- ### jest.fn() 首先來看一下範例程式碼,我們有兩個函式,其中 `checkRareMagicAttributes` 函式幫我們確認是否為稀有魔法屬性,而 `calculateRareAttributesTotal` 函式幫忙計算總人數,當在執行 `calculateRareAttributesTotal` 函式時是會透過傳入的 `checkRareMagicAttributes` 函式來幫我們確認稀有屬性的人數: ```jsx! const quizList = [ { name: "艾草", attributes: "木" }, { name: "Vivian", attributes: "火" }, { name: "啾啾", attributes: "光" } ]; // 確認是否為稀有魔法屬性 function checkRareMagicAttributes(attributes) { if (attributes === "光" || attributes === "暗") { return true; } else { return false; } } // 確認屬性稀有屬性人數 function calculateRareAttributesTotal(data) { let total = 0; data.forEach((item) => { if (checkRareMagicAttributes(item.attributes)) { total += 1; } }); return total; } ``` 當針對 `calculateRareAttributesTotal` 撰寫測試而不希望實際去執行 `checkRareMagicAttributes` 函式時,可以透過 **`mock`** 來幫忙實現: 1. 首先透過 jest.fn() 來模擬一個函式: ```jsx test('Introducing mocks', () => { // arrange // 模擬 const mockFunction = jest.fn(); checkRareMagicAttributes = mockFunction; }); ``` 2. 接著透過 Jest 提供的方法來設定回傳值: - `mockFn.mockReturnValue(value)`:mock 每次的回傳值 - `mockFn.mockReturnValueOnce(value)` :mock 一次回傳值,當沒有設定 `mockReturnValueOnce` 後會回傳 `mockReturnValue` 設定的回傳值 ```jsx test("Introducing mocks", () => { // arrange const mockFunction = jest.fn(); checkRareMagicAttributes = mockFunction; // 設定回傳值 mockFunction.mockReturnValue(false).mockReturnValueOnce(true); }); ``` 3. 斷言結果:可以透過 calculateRareAttributesTotal 回傳值及 toHaveBeenCalled 來判斷是否有成功呼叫 mockFunction 來斷言。 ```jsx test("Introducing mocks", () => { // arrange const mockFunction = jest.fn(); checkRareMagicAttributes = mockFunction; mockFunction.mockReturnValue(false).mockReturnValueOnce(true); // act const result = calculateRareAttributesTotal(quizList); // assert expect(calculateRareAttributesTotal(quizList)).toBe(1); expect(mockFunction).toHaveBeenCalled(); }); ``` 像這樣就透過 jest.fn() 的方式成功模擬一個函式! ### 模擬函式回傳的其他方法 **jest.fn()** 除了可以透過 `mockReturnValue` 來模擬回傳值外,還有 `mockImplementation` 方法,可以直接傳入一個模擬函式。 ```jsx // 範例程式碼取自官方文件 const mockFn = jest.fn(scalar => 42 + scalar); mockFn(0); // 42 mockFn(1); // 43 mockFn.mockImplementation(scalar => 36 + scalar); mockFn(2); // 38 mockFn(3); // 39 ``` 透過 Jest.fn() 可以更方便模擬依賴函式或套件! --- ### spyOn() 透過 spyOn 的方式改寫,spyOn 與 jest.fn() 相似都可以模擬函式,與之不同的是 spyOn 會真的去**執行該函式**。 spyOn 需帶入兩個參數: ```jsx jest.spyOn(object, methodName) // 物件名稱, 物件內的方法名稱 ``` 1. 物件名稱 2. 物件內的方法名稱 改寫上面範例程式碼,將範例程式碼的 `checkRareMagicAttributes` 放到一個物件內: ```jsx! const quizList = [ { name: "艾草", attributes: "木" }, { name: "Vivian", attributes: "火" }, { name: "啾啾", attributes: "光" } ]; // 確認是否為稀有魔法屬性 const object = { checkRareMagicAttributes: (attributes) => { if (attributes === "光" || attributes === "暗") { return true; } else { return false; } } } // 確認屬性稀有屬性人數 function calculateRareAttributesTotal(data) { let total = 0; data.forEach((item) => { // 透過 checkRareMagicAttributes 的回傳值為 true / false 判斷是否為光暗屬性 if (checkRareMagicAttributes(item.attributes)) { total += 1; } }); return total; } ``` 👉 當針對 `calculateRareAttributesTotal` 撰寫測試且希望有去執行 `checkRareMagicAttributes` 函式時,可以透過 `spyOn` 來幫忙實現: 1. 首先透過 `spyOn`,並帶入物件名稱及方法名稱 `checkRareMagicAttributes`: ```jsx test("Introducing spyOn", () => { // arrange const spyOnFunction = jest.spyOn(object,"checkRareMagicAttributes"); }); ``` 2. 接著透過 result 來執行行動 ```jsx test("Introducing spyOn", () => { // arrange const spyOnFunction = jest.spyOn(object,"checkRareMagicAttributes"); // act const result = calculateRareAttributesTotal(quizList); }); ``` 3. 斷言結果:可以透過 `calculateRareAttributesTotal` 回傳值及 `toHaveBeenCalledTimes` 來判斷是否有成功呼叫 `spyOnFunction` 來斷言,這邊因為資料有三筆物件,所以共呼叫了三次 `spyOnFunction`。 ```jsx! test("Introducing spyOn", () => { // arrange const spyOnFunction = jest.spyOn(object,"checkRareMagicAttributes"); // act const result = calculateRareAttributesTotal(quizList); // assert expect(result).toBe(1); expect(spyOnFunction).toHaveBeenCalledTimes(3); }); ``` 像這樣就透過 spyOn 模擬成功! -- #### 可用 mockRestore() 恢復原始函式 `spyOn` 也可以使用 `mock` 的方法如 `mockImplementation` 等模擬回傳函式,而當想調用原始函式而不掉用模擬函式時 `spyOn` 還可以使用 `mockRestore()`` 的方式將模擬的函式改回原本函式,可用於多個測試其中一項須改回原本函式時。 --- 參考文章 https://jestjs.io/zh-Hans/docs/mock-functions https://jestjs.io/docs/mock-function-api https://medium.com/enjoy-life-enjoy-coding/jest-jojo是你-我的替身能力是-mock-4de73596ea6e https://blog.jimmydc.com/mock-asynchronous-functions-with-jest/ https://vhudyma-blog.eu/3-ways-to-mock-axios-in-jest/ https://www.youtube.com/watch?v=1Xafx6o82Aw&ab_channel=SoftwareTestingHelp https://dwatow.github.io/2020/04-24-jest/jest-doc-5/ https://jestjs.io/docs/jest-object#jestspyonobject-methodname https://medium.com/enjoy-life-enjoy-coding/jest-jojo是你-我的替身能力是-mock-4de73596ea6e https://www.youtube.com/watch?v=1Xafx6o82Aw&ab_channel=SoftwareTestingHelp https://dwatow.github.io/2020/04-24-jest/jest-doc-5/

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully