【问题标题】:Reset an ES6 module with SystemJS (for unit tests)?使用 SystemJS 重置 ES6 模块(用于单元测试)?
【发布时间】:2016-01-21 04:27:23
【问题描述】:

我们的工作流程包括使用 ES6 模块。这也包括单元测试。我们import 正在测试的模块。问题是原作者决定让每个模块都返回对象,因此我们在整个代码库中都有全局单例(因为 ES6 导入的工作原理)——这是一个经典的单元测试问题。

有没有办法在每次测试后用 SystemJS “重置”所述模块?

示例单元测试(由 karma-systemjs 加载):

import MUT from './Mut' // module under test

describe('MUT', () => {

   it('should do stuff', () => {

      MUT.value = 'foo'
   })

   it('should do more stuff', () => {

      // value should not be 'foo' here. How do you reset MUT?
   })

【问题讨论】:

    标签: unit-testing jasmine karma-runner systemjs


    【解决方案1】:

    查看 Github 上的 this issue,尤其是 this comment

    尝试在 beforeEach 块中删除然后重新导入模块,如下所示:

    describe('MUT', () => {
    
      let MUT;
    
      beforeEach((done) => {
        // remove the previous version
        System.delete(System.normalizeSync('./Mut'))
        // re-import the module
        System.import('./Mut').then((imported) => {
          MUT = imported
        }).then(done, fail)
      })
    
      it('should do stuff, () => {
        MUT.value = 'foo'
        expect(MUT.value).toBe('foo')
      })
    
      it('should do more stuff', () => {
        expect(MUT.value).not.toBe('foo')
      })
    
    })
    

    【讨论】:

    • 是的,我想我们试过了。问题是 Mut 的依赖也需要重新加载
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2012-06-25
    • 2015-02-04
    相关资源
    最近更新 更多