如何使用Jest监视默认的导出功能?

时间:2019-01-17 23:15:24

标签: reactjs unit-testing mocking jestjs spy

假设我有一个导出默认功能的简单文件:

String masterKeyUri = "aws-kms://arn:aws:kms:us-east-1:007084425826:key/84a65985-f868-4bfc-83c2-366618acf147";
KeysetHandle keysetHandle = KeysetHandle.read(
        JsonKeysetReader.withFile(new File(keysetFilename)),
        new AwsKmsClient().withDefaultCredentials().getAead(masterKeyUri))

我会这样使用:

// UniqueIdGenerator.js
const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);

export default uniqueIdGenerator;

我想在测试中断言在保持原始功能的同时调用了此方法。我会用import uniqueIdGenerator from './UniqueIdGenerator'; // ... uniqueIdGenerator(); 来做,但是它需要一个对象以及一个函数名作为参数。如何以一种干净的方式做到这一点?有兴趣的人可以为jest.spyOn使用类似的GitHub issue

4 个答案:

答案 0 :(得分:2)

仍然愿意接受建议,但我所做的却是放弃了默认导出:

// UniqueIdGenerator.js
export const uniqueIdGenerator = () => Math.random().toString(36).substring(2, 8);

然后我可以像这样使用和监视它:

import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'uniqueIdGenerator');

Some recommend将它们包装在const对象中,然后导出。我想您也可以使用包装类。

但是,如果您不能修改类,那么仍然有一个(不太好的)解决方案:

import * as UniqueIdGenerator from './UniqueIdGenerator';
// ...
const spy = jest.spyOn(UniqueIdGenerator, 'default');

答案 1 :(得分:1)

在某些情况下,您必须模拟导入才能监视默认导出:

spring:
    http:
        multipart:
            max-file-size: 10MB
            max-request-size: 10MB

答案 2 :(得分:0)

也可以模拟导入并将原始实现作为模拟实现传递,例如:

import uniqueIdGenerator from './UniqueIdGenerator'; // this import is a mock already

jest.mock('./UniqueIdGenerator.js', () => {
  const original = jest. requireActual('./UniqueIdGenerator')
  return {
     __esModule: true,
     default: jest.fn(original.default)
  }
})

test(() => {
  expect(uniqueIdGenerator).toHaveBeenCalled()
})

答案 3 :(得分:-1)

对我有用的是来自 Janne Annala 的答案和 OP 自己的解决方案的组合。我想要测试的只是辅助方法是否使用正确的参数调用,因为我已经为辅助方法编写了测试,并且它对我后续的测试没有任何影响:

// myHelperMethod.js

export const myHelperMethod = (param1, param2) => { // do something with the params };
// someOtherFileUsingMyHelperMethod.js

import * as MyHelperMethod from '../myHelperMethod';


jest.mock('../myHelperMethod', () => ({
  myHelperMethod: jest.fn(),
}));

let myHelperMethodSpy = jest.spyOn(MyHelperMethod, 'myHelperMethod');

// ...
// some setup
// ...

test(() => {
  expect(myHelperMethodSpy).toHaveBeenCalledWith(param1, param2);
});
相关问题