Javascript 在jest模拟中指定函数参数
我目前正在编写单元测试来提高我的覆盖率,我被困在一个函数上,我想设置一个函数的输入参数 我想测试的功能是:Javascript 在jest模拟中指定函数参数,javascript,typescript,unit-testing,testing,jestjs,Javascript,Typescript,Unit Testing,Testing,Jestjs,我目前正在编写单元测试来提高我的覆盖率,我被困在一个函数上,我想设置一个函数的输入参数 我想测试的功能是: this.map.forEachFeatureAtPixel(e.pixel, (event: any) => { if ( event.values_.name === 'name' ) { this.openWeatherData(event.values_.name); } //more logic ... }); 我想测试
this.map.forEachFeatureAtPixel(e.pixel, (event: any) => {
if (
event.values_.name === 'name'
) {
this.openWeatherData(event.values_.name);
} //more logic ...
});
我想测试回调函数中的代码,以测试是否进行了正确的调用
但是如何将事件参数设置为
{ values_ : { name: 'name' } }
并执行实际回调实现以提高覆盖率。用于为此.map.forEachFeatureAtPixel()方法及其模拟实现创建模拟版本。模拟实现接受两个参数:pixel
和callback
。使用模拟事件对象手动调用回调
函数
例如
index.ts
:
export const obj = {
map: {
// simulate real implementation
forEachFeatureAtPixel(pixel, callback) {
callback();
},
},
method(e) {
this.map.forEachFeatureAtPixel(e.pixel, (event: any) => {
if (event.values_.name === 'name') {
console.log('openWeatherData');
}
});
},
};
import { obj } from './';
describe('67818053', () => {
it('should pass', () => {
const mEvent = { values_: { name: 'name' } };
const forEachFeatureAtPixelSpy = jest
.spyOn(obj.map, 'forEachFeatureAtPixel')
.mockImplementationOnce((pixel, callback) => {
callback(mEvent);
});
obj.method({ pixel: '12' });
expect(forEachFeatureAtPixelSpy).toBeCalledWith('12', expect.any(Function));
forEachFeatureAtPixelSpy.mockRestore();
});
});
index.test.ts
:
export const obj = {
map: {
// simulate real implementation
forEachFeatureAtPixel(pixel, callback) {
callback();
},
},
method(e) {
this.map.forEachFeatureAtPixel(e.pixel, (event: any) => {
if (event.values_.name === 'name') {
console.log('openWeatherData');
}
});
},
};
import { obj } from './';
describe('67818053', () => {
it('should pass', () => {
const mEvent = { values_: { name: 'name' } };
const forEachFeatureAtPixelSpy = jest
.spyOn(obj.map, 'forEachFeatureAtPixel')
.mockImplementationOnce((pixel, callback) => {
callback(mEvent);
});
obj.method({ pixel: '12' });
expect(forEachFeatureAtPixelSpy).toBeCalledWith('12', expect.any(Function));
forEachFeatureAtPixelSpy.mockRestore();
});
});
测试结果:
PASS examples/67818053/index.test.ts (8.297 s)
67818053
✓ should pass (14 ms)
console.log
openWeatherData
at examples/67818053/index.ts:11:17
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.055 s