首页 > 解决方案 > 如何在玩笑中配置所有 cmmon 文件?

问题描述

如何在 jest.config 中加载所有常用文件

如何加载所有常见文件和 3td 方库,如 jquery

{
  "name": "my-project",
  "jest": {
    setupFiles:[../src/assert]
  }
} 

标签: jestjsbabel-jest

解决方案


您可以. jest.config.jsjqueryand分配moment给 node.jsglobal对象。global.$然后,您可以使用和在每个测试用例中获取它们global.moment

例如

setup.js

const jquery = function () {
  return "I'm fake jquery";
};
const moment = function () {
  return "I'm fake moment";
};

global.$ = jquery;
global.moment = moment;

jest.config.js

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: [
    'jest-enzyme',
    './jest.setup.js',
  ],
  setupFiles: [
    '/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/61727628/setup.js',
  ],
  testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
  verbose: true,
};

a.test.js

describe('61727628', () => {
  describe('a', () => {
    it('should pass', () => {
      console.log('global.$:', global.$);
      console.log('global.moment:', global.moment);
      expect(1 + 1).toBe(2);
    });
  });
});

b.test.js

describe('61727628', () => {
  describe('b', () => {
    it('should pass', () => {
      console.log('global.$:', global.$);
      console.log('global.moment:', global.moment);
      expect(1 + 1).toBe(2);
    });
  });
});

单元测试结果:

 PASS  stackoverflow/61727628/a.test.js
  61727628
    a
      ✓ should pass (28ms)

  console.log
    global.$: function () {
        return "I'm fake jquery";
    }

      at Object.<anonymous> (stackoverflow/61727628/b.test.js:4:15)

  console.log
    global.$: function () {
        return "I'm fake jquery";
    }

      at Object.<anonymous> (stackoverflow/61727628/a.test.js:4:15)

  console.log
    global.moment: function () {
        return "I'm fake moment";
    }

      at Object.<anonymous> (stackoverflow/61727628/a.test.js:5:15)

  console.log
    global.moment: function () {
        return "I'm fake moment";
    }

      at Object.<anonymous> (stackoverflow/61727628/b.test.js:5:15)

 PASS  stackoverflow/61727628/b.test.js
  61727628
    b
      ✓ should pass (28ms)

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        6.026s, estimated 16s

推荐阅读