Javascript 代码覆盖率不为';t到达空集函数

Javascript 代码覆盖率不为';t到达空集函数,javascript,jestjs,Javascript,Jestjs,即使我正在测试某些代码行,代码覆盖率也没有达到:( 这是我创建的bind.ts decorator和[[notcovered]]代码覆盖率标记。当前,该集(值)未被测试覆盖,即使我正在覆盖它 type Descriptor<T> = TypedPropertyDescriptor<T>; export default function bind<T = Function>( target: object, key: string, descrip

即使我正在测试某些代码行,代码覆盖率也没有达到:(

这是我创建的bind.ts decorator和[[notcovered]]代码覆盖率标记。当前,该集(值)未被测试覆盖,即使我正在覆盖它

type Descriptor<T> = TypedPropertyDescriptor<T>;

export default function bind<T = Function>(
  target: object,
  key: string,
  descriptor: Descriptor<T>
): Descriptor<T> {
  ...
    set(value: T): void {
    [[22-NOT COVERED]]  if (process.env.NODE_ENV !== 'test') {
    [[23-NOT COVERED]]    throw new Error('Unable to set new value to decorated method');
    [[24-NOT COVERED]]  }
    [[25-NOT COVERED]]  Object.defineProperty(this, key, { ...descriptor, value });
    },
  };
}

类型描述符=类型属性描述符;
导出默认函数绑定(
目标:目标,,
键:字符串,
描述符:描述符
):描述符{
...
设置(值:T):无效{
[[22-未涵盖]]如果(process.env.NODE_env!=“测试”){
[[23-未涵盖]]抛出新错误(“无法为修饰方法设置新值”);
[[24-未涵盖]]}
[[25-未涵盖]]Object.defineProperty(this,key,{…描述符,value});
},
};
}
bind.spec.ts 我的策略是创建新的类组件并在调用时测试其上下文

class MockClass extends React.PureComponent<Props, State> {
  @bind
  getProp(): string {
    const { propName } = this.props;
    return propName;
  }

  @bind
  getState(): string {
    const { stateName } = this.state;
    return stateName;
  }

  @bind
  setProp(value: string): void {
    this.state = { stateName: value };
  }
}

...

describe('bind', () => {
  const mockState = {
    stateName: 'stateName',
  };

  const mockProp = {
    propName: 'propName',
  };

  const mockClass = new MockClass(mockProp, mockState);

  ...

  it('should have called it once', () => {
    expect(mockClass.getProp()).toBe(mockProp.propName);
  });

  it('should have called it in setState', () => {
    expect(mockClass.setProp('newState')).toBe(undefined); <<<- This can cover 22-25??
  });
class MockClass扩展了React.PureComponent{
@束缚
getProp():字符串{
const{propName}=this.props;
返回propName;
}
@束缚
getState():字符串{
const{stateName}=this.state;
返回stateName;
}
@束缚
setProp(值:字符串):无效{
this.state={stateName:value};
}
}
...
描述('bind',()=>{
常数mockState={
stateName:“stateName”,
};
常量mockProp={
propName:“propName”,
};
const mockClass=新mockClass(mockProp,mockState);
...
它('应该叫它一次',()=>{
expect(mockClass.getProp()).toBe(mockProp.propName);
});
它('应该在setState中调用它',()=>{

expect(mockClass.setProp('newState')).toBe(undefined);未覆盖的setter是在设置class属性值时可以执行的代码。您没有任何测试代码可以执行此操作。您只获得一个名为
setProp
的属性,然后调用它。该属性具有“set”的事实以它的名义可能会令人困惑

您的测试代码必须执行以下操作才能测试装饰器的setter:

mockClass.props.otherPropName = 'blah';
mockClass.getProp = function() {
  const { otherPropName } = this.props;
  return otherPropName;
};
expect(mockClass.getProp()).toEqual('blah');

谢谢@Jacob。但是我在
otherPropName
上得到了这个erorr:无法分配给“otherPropName”,因为它是只读属性。ts(2540)getter覆盖该属性,使其成为只读:
Object.defineProperty(this,key,{…descriptor,value});