简体   繁体   English

如何在 Jest 中模拟局部变量以进行单元测试?

[英]How to mock Local Variables for unit testing in Jest?

I have two files, file.component.ts containing:我有两个文件, file.component.ts包含:

  setTwoNumberDecimal(e) {
    const USER_VAL = parseFloat(e.target.value.replace(/,/g, ''));
    e.target.value = this.getTruncatedValue(USER_VAL, 1);
  }

and my test file file.component.specs.ts containing:和我的测试文件file.component.specs.ts包含:

describe('setTwoNumberDecimal()', () => {
  it('tests commas are removed and user value is set', () => {
    const mockEvent = {target: {value: '5.777,'}};
    component.setTwoNumberDecimal(mockEvent);
    expect(component.setTwoNumberDecimal).toHaveBeenCalled();
  });
});

I want to be able to check that, after setTwoNumberDecimal(e) is run:我希望能够在运行setTwoNumberDecimal(e)之后进行检查:

  1. USER_VAL is equal to '5.777' (that is, the comma has been removed); USER_VAL等于'5.777' (即去掉逗号); and

  2. e.target.value is equal to '5.77' (that is, the last value has been truncated) e.target.value is equal '5.77' (即最后一个值已被截断)

The functionality already works for the comma replace and the truncate.该功能已经适用于逗号替换和截断。

Test that the value is what you expect it to be in your mocked event.测试该值是否符合您在模拟事件中的预期值。

describe('setTwoNumberDecimal()', () => {
  it('Should truncate decimal from value', () => {
    const mockEvent = {target: {value: '5.777,'}};
    expect(mockEvent.target.value).toEqual('5.77');
  });
  it('Should remove commas from value', () => {
    const mockEvent = {target: {value: '1,234,567.89,'}};
    expect(mockEvent.target.value).toEqual('1234567.89');
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM