首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mocha - moch在测试环境之外导入

Mocha - moch在测试环境之外导入
EN

Stack Overflow用户
提问于 2022-05-20 01:04:46
回答 1查看 21关注 0票数 0

不确定这是否可行,我有一个在100+文件中使用的助手方法:

代码语言:javascript
复制
// helpers.ts
// exports a json object using export default
import STATIC_DATA from '@data/static-data';

export function getData(key: StaticDataKey) {
    return STATIC_DATA[key].include ? 'foo' : 'bar';
}

这个助手方法做了更多的工作,但是我简化了我的示例

在测试环境中

代码语言:javascript
复制
import assert from 'assert';

it('should return foo when include is true', () => {
   const isFoo = getData('someKey');
   assert.equal(isFoo, 'foo');
});

it('should return bar when include is false', () => {
   const isBar = getData('someOtherKey');
   assert.equal(isBar, 'bar');
});

我想要做的是,在每个测试中模拟在helpers.ts文件中导入的“helpers.ts”是什么,这样我就可以强制数据达到我想要的结果,所以测试始终是真实的(例如,我知道它不起作用)。

代码语言:javascript
复制
it('should return bar when include is false', () => {
   proxyquire('@data/static-data', {
        someOtherKey:{
            include: false
        }

   });
   const isBar = getData('someOtherKey');
   assert.equal(isBar, 'bar');
});

我试过使用nock,sinon,proxyrequire,但没有成功

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-20 03:16:56

只需在每个测试用例中将测试数据设置为STATIC_DATA,并在每个测试用例结束时清除它。

static-data.ts

代码语言:javascript
复制
export default {};

helper.ts

代码语言:javascript
复制
import STATIC_DATA from './static-data';

export function getData(key) {
  return STATIC_DATA[key].include ? 'foo' : 'bar';
}

helper.test.ts

代码语言:javascript
复制
import { getData } from './helper';
import sinon from 'sinon';
import STATIC_DATA from './static-data';

describe('72312542', () => {
  it('should return bar when include is false', () => {
    STATIC_DATA['someOtherKey'] = { include: false };
    const isBar = getData('someOtherKey');
    sinon.assert.match(isBar, 'bar');
    delete STATIC_DATA['someOtherKey'];
  });

  it('should return foo when include is true', () => {
    STATIC_DATA['someKey'] = { include: true };
    const isFoo = getData('someKey');
    sinon.assert.match(isFoo, 'foo');
    delete STATIC_DATA['someKey'];
  });
});

测试结果:

代码语言:javascript
复制
  72312542
    ✓ should return bar when include is false
    ✓ should return foo when include is true


  2 passing (4ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |     100 |      100 |     100 |     100 |                   
 helper.ts      |     100 |      100 |     100 |     100 |                   
 static-data.ts |     100 |      100 |     100 |     100 |                   
----------------|---------|----------|---------|---------|-------------------
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72312542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档