使用 Jest 在导入的模块中模拟外部用户模块

ben*_*e89 3 javascript jestjs

我不知道我是否在文档中遗漏了什么,但我有这种情况:

// 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
  }
}
Run Code Online (Sandbox Code Playgroud)

什么是玩笑,方法,以防止/嘲笑外部Api模块User.js。我不想User.js在测试中发出真实的网络请求。

除此之外,我正在寻找更通用的模拟解决方案,即。假设我正在 React Native 中进行测试,并且我想模拟NativeModules.SettingsManager.settings.AppleLocale,例如。假设Api.fetch()调用上面的行,并且不发出 HTTP 请求

Bri*_*ams 5

spyOnmockImplementation模拟功能相结合将提供您正在寻找的内容。

这是一个工作示例:

// ---- 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
  });
});
Run Code Online (Sandbox Code Playgroud)