簡體   English   中英

使用Jest模擬導入模塊中的外部用戶模塊

[英]Use Jest to mock external user module in an imported module

我不知道文檔中是否缺少某些內容,但是我有這種情況:

// test.js

import User from './user'

it("should load initial data", async() => {
  const users = new User()
  const user = await users.load()
})

// User.js

import Api from './api'

export default class User {
  async load() {
    const res = await Api.fetch() // prevent/mock this in testing
  }
}

防止/嘲笑User.js的外部Api模塊的開玩笑的方法是什么。 我不希望User.js在測試中發出真實的網絡請求。

除此之外,我正在尋找更通用的模擬解決方案,即。 說我正在React Native中進行測試,例如,我想模擬NativeModules.SettingsManager.settings.AppleLocale 可以說Api.fetch()調用上面的行,並且不發出HTTP請求

spyOn結合模擬函數(例如mockImplementation)將為您提供所需的內容。

這是一個工作示例:

// ---- api.js ----
export const getData = () => {
  return Promise.resolve('hi');
}


// ---- user.js ----
import { getData } from './api'

export default class User {
  async load() {
    return await getData(); // mock this call in user.test.js
  }
}


// ---- user.test.js ----
import User from './user'
import * as Api from './api'; // import * so we can mock 'getData' on Api object

describe('User', () => {
  it('should load initial data', async() => {
    const mock = jest.spyOn(Api, 'getData'); // create a spy
    mock.mockImplementation(() => Promise.resolve('hello')); // give it a mock implementation

    const user = new User();
    const result = await user.load();
    expect(result).toBe('hello');  // SUCCESS, mock implementation called

    mock.mockRestore(); // restore original implementation when we are done
  });
});

如果您需要模擬對HTTP請求的響應,則應查看nock 它具有干凈的API,在創建對特定請求的HTTP響應時具有很大的靈活性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM