简体   繁体   English

Jest mocking 模块导出 class 和功能

[英]Jest mocking module that exports a class and functions

I have a module that exports a class and 2 functions and that module is imported into a file that is being tested.我有一个导出 class 和 2 个函数的模块,并且该模块被导入到正在测试的文件中。

someFile.js
const {theclass, thefunction} = require("theModule");

const getSomeFileData = () => {
   let obj = new theclass();
   //some logic
   return obj.getData();
}

In the test file, I want to mock the module "theModule" and return a known value when the function obj.getData() is called.在测试文件中,我想模拟模块“theModule”并在调用 function obj.getData() 时返回一个已知值。 How would I go about mocking this module("theModule") when testing file "someFile.js"?在测试文件“someFile.js”时,我将如何 go 关于 mocking 这个模块(“theModule”)?

Edit:编辑:

.spec.ts .spec.ts

import { someFunction } from './index-test';

jest.mock('lodash', () => {
  return {
    uniqueId: () => 2,
  };
});

describe('', () => {
  it('', () => {
    expect(someFunction()).toBe(2);
  });
});

index-test.ts索引测试.ts

import { uniqueId } from 'lodash';

export const someFunction = () => {
  return uniqueId();
};

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

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