How to mock dependencies for unit tests with ES6 Modules

后端 未结 5 1312
一整个雨季
一整个雨季 2020-12-02 11:58

I\'m trying to fiddle with Ecmascript 6 modules using webpack + traceur to transpile to ES5 CommonJS, but I\'m having trouble successfully unit testing them.

I tried

5条回答
  •  温柔的废话
    2020-12-02 12:40

    If you are using Webpack another option that has a little more flexibility than rewire is inject-loader.

    For example, in a test that is bundled with Webpack:

    describe('when an alert is dismissed', () => {
    
      // Override Alert as we need to mock dependencies for these tests
      let Alert, mockPubSub
    
      beforeEach(() => {
        mockPubSub = {}
        Alert =  require('inject!./alert')({
          'pubsub-js': mockPubSub
        }).Alert
      })
    
      it('should publish \'app.clearalerts\'', () => {
        mockPubSub.publish = jasmine.createSpy()
        [...]
        expect(mockPubSub.publish).toHaveBeenCalled()
      })
    })
    

    inject-loader, in a similar manner to proxyquire at least allows one to inject dependencies before importing whereas in rewire you must import first and then rewire which makes mocking some components (e.g. those that have some initialization) impossible.

提交回复
热议问题