首页 > 解决方案 > 导出类和函数的 Jest 模拟模块

问题描述

我有一个导出一个类和 2 个函数的模块,并且该模块被导入到一个正在测试的文件中。

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

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

在测试文件中,我想模拟模块“theModule”并在调用函数 obj.getData() 时返回一个已知值。在测试文件“someFile.js”时,我将如何模拟这个模块(“theModule”)?

标签: javascriptnode.jstestingjestjsmocking

解决方案


编辑:

.spec.ts

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

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

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

索引测试.ts

import { uniqueId } from 'lodash';

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

推荐阅读