javascript - 如何在茉莉花中模拟请求
问题描述
如何在此函数中模拟请求。我想使用 jasmine 对这个函数进行单元测试。
function getProducts() {
return new Promise((resolve, reject) => {
request.get(
{
url: 'http://ascott.com/products'
},
(err, response, body) => {
if (err) return reject(err);
const result = JSON.parse(body);
if(result.value =='yes') return resolve(1);
return resolve(0);
}
);
});
}
解决方案
使用spyOn(obj, methodName)函数将 spy 安装到request.get()
方法上,然后使用callFake(fn)
告诉 spy 在调用时调用假实现。这样您就可以在假实现中触发回调。
index.js
:
import request from 'request';
export function getProducts() {
return new Promise((resolve, reject) => {
request.get({ url: 'http://ascott.com/products' }, (err, response, body) => {
if (err) return reject(err);
const result = JSON.parse(body);
if (result.value == 'yes') return resolve(1);
return resolve(0);
});
});
}
index.test.js
:
import { getProducts } from '.';
import request from 'request';
describe('69769551', () => {
it('should return 1', async () => {
spyOn(request, 'get').and.callFake((_, callback) => {
callback(null, null, JSON.stringify({ value: 'yes' }));
});
const actual = await getProducts();
expect(actual).toEqual(1);
});
it('should throw error', async () => {
const mError = new Error('network');
spyOn(request, 'get').and.callFake((_, callback) => {
callback(mError);
});
await expectAsync(getProducts()).toBeRejectedWithError('network');
});
});
测试结果:
Executing 2 defined specs...
Running in random order... (seed: 04537)
Test Suites & Specs:
1. 69769551
✔ should throw error (7ms)
✔ should return 1 (1ms)
>> Done!
Summary:
Passed
Suites: 1 of 1
Specs: 2 of 2
Expects: 2 (0 failures)
Finished in 0.017 seconds
包版本:
"jasmine": "^3.6.3"
"request": "^2.88.2"
推荐阅读
- python - 提取两个字符之间的子字符串 - python DataFrame
- c++ - 如何洗牌 std::map 中的元素键?
- android - “应用程序”已停止 android studio 调试
- angular - 从头开始构建具有 Angular 2+ 和 Spring Boot 的 Web 应用程序?
- android - 找不到任何与 com.google.android.gms:play-services:[15.0.0, 16.0.0) 匹配的版本
- javascript - 如何删除html中标签中关联的所有属性和值
- mysql - 在 prestashop 中更新产品后更改 phmyadmin 中的默认类别
- ios - 如何修复 Apple Mach-O 链接器(ld)错误组 - ld:找不到 -lFBSDKCoreKit 的库
- ios - 将核心数据添加到现有项目时出现 Swift 编译器错误
- java - 如何从另一个函数/方法调用变量?