【问题标题】:Unit test for a function calling another function using jest使用 jest 对调用另一个函数的函数进行单元测试
【发布时间】:2018-11-20 21:00:26
【问题描述】:

我是 Jest 的新手,在编写单元测试时遇到了一些问题。 我的函数正在调用另一个带有一些参数的匿名函数。

你能帮我解决它吗?

const myFunctionToTest = (code, data) => (isValid, availableCodes, defaultValue) => {
    if(isValid) {
        const isAvailableCode = isEmpty(availableCodes) || includes(availableCodes, code);
        return isAvailableCode ? get(data, 'originalQty') : defaultValue;
    }   
    return defaultValue;
};

这是模拟数据:

模拟数据:

code: 'AB'
data: { originalQty : 2 };
isValid: true;
availableCodes: ['BCD', 'AB'];
defaultValue: 0;

我试过了!

describe('myFunctionToTest', () => {
  test('it should return originally assigned quantity', () => {
    const result = myFunctionToTest('AB', { originalQty: 2 } , () => {true, ['BCD', 'AB'], 0});
    expect(result).toEqual(2);
  });
});

【问题讨论】:

  • 一些问题 - 什么问题?该问题缺少问题陈述。它还缺少 stackoverflow.com/help/mcve ,有几个函数如 isEmpty 没有列出。
  • isEmpty, get 和 includes 是 'lodash' 方法,我们不需要在这里测试它们。我面临的问题是 - “预期的数量,但收到的功能。”

标签: reactjs function unit-testing ecmascript-6 jestjs


【解决方案1】:

好的,我明白了。 这是我试过的!

describe('myFunctionToTest', () => {
  test('it should return originally assigned quantity', () => {
    const result = myFunctionToTest('AB', { originalQty: 2 });
    expect(result(true, ['BCD', 'AB'], 0).toEqual(2);
  });
});

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多