如何用Jest模拟咖喱功能?

时间:2018-02-21 12:29:00

标签: jestjs

add.js

<my-app bodyData="passed" ></my-app>

module.js

@Component({
  selector: 'my-app',
  template: `
    (...)
  `
})
export class MyAppComponent {
  constructor(private eltRef:ElementRef) {
    let prop = eltRef.getAttribute('bodyData');
  }
}

测试 /module.js

export default a => b => a+b;

这可以调用,但import add from './add'; export default { add1: n => add(1)(n), }; 不是模拟函数,而import add from '../add'; import module from '../module'; jest.mock('../add', () => () => jest.fn()); module.add1(6); expect(add.mock.calls).toHaveLength(1); 是模拟函数,但调用参数没有正确记录。

add

也尝试了这个,但似乎也没有正常工作。

add()

这会抛出jest.mock('../add', () => () => jest.fn(a => b => a+b)); 错误

目前是否有正确的方法来模拟咖喱功能?

3 个答案:

答案 0 :(得分:2)

简单版本应该如下所示

jest.mock('../add', () => (a) => jest.fn(b => a+b));

所以你用一个函数来模拟add模块,该函数在被调用时返回它返回间谍,你可以在间谍上测试任何东西的问题。

因此我们需要对其进行重构,以便让add1认为是测试范围内的间谍

import add from '../add'
jest.mock('../add', () => jest.fn)

const addC = jest.fn()
add.mockImplemetation((a) => {
  addC.mockImplementation((b => a+b)
  return addC
})

答案 1 :(得分:1)

我知道这有点旧,但是通过以下回答,我可以节省很多时间...

data.frame(m) %>%
    mutate(rows = rownames(.)) %>%
    gather(cols, val, -rows) %>%
    filter(val != Inf)

非常重要的事情:要模拟的常量函数必须以单词import module from "./module"; const mockOperation = { add: jest.fn() }; jest.mock("./add", () => () => { return mockOperation.add; }); describe("add ", () => { it("is called at least once", () => { module.add1(6); expect(mockOperation.add.mock.calls).toHaveLength(1); }); }); 开头。否则会引发错误。

mock

在将const mockOperation = { add: jest.fn() }; 常量分配给添加文件的情​​况下,通过引用调用它的mockOperation方法,即add

答案 2 :(得分:0)

我最近不得不这样做很多,所以我写了一个辅助函数来帮助我。

curryMock = (baseFn, maxCurries) => {
    var callIndex = 0
    var curries = []
    let returnFn

    baseFn.mockImplementation((arg) => {
        curries[callIndex] = 0
        const fn = returnFn(callIndex)
        callIndex++
        return fn
    })

    returnFn = (index: number) => {
        if (curries[index] < maxCurries) {
            curries[index]++
            return (arg: any) => {
                baseFn.mock.calls[index].push(arg)
                return returnFn(index)
            }
        }
    }
}

您将函数传递给 jest.fn() 并 curryMock 修改它的实现,以便调用的所有参数返回函数都将添加到原始 jest.fn().mock.calls 数组中。第二个参数指定返回函数的次数。 maxCurries = 0 用于常规函数 () => {}, maxCurries = 1is for a regular function() => => {}` 等

就你而言:

import add from '../add';
import module from '../module';

jest.mock('../add');
curryMock(add)

module.add1(6);
expect(add).toHaveBeenCalledWith(1, 6);
//equivalent to
//expect(add).toHaveBeenNthCalledWith(1, 1, 6);

//if you others to test..
module.add7(4)
expect(add).toHaveBeenNthCalledWith(2, 7, 4)

curryMock 是我为个人使用而编写的快速实用函数。我可能会在稍后对其进行清理和扩展,但我希望你能明白:测试柯里化函数不必费力。

相关问题