我不知道我是否遗漏了文档中的某些内容,但我遇到了这种情况:
// 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
模块的 Jest-way 是什么。我不希望 User.js
在测试中发出真实的网络请求。
除此之外,我正在寻找更通用的模拟解决方案,即。例如,假设我正在 React Native 中进行测试,并且我想模拟 NativeModules.SettingsManager.settings.AppleLocale
。比方说 Api.fetch()
调用上面的行,并且不发出 HTTP 请求
最佳答案
spyOn结合mock functions喜欢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
});
});
关于javascript - 使用 Jest 模拟导入模块中的外部用户模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825420/