How can I mock the imports of an ES6 module?

后端 未结 8 1478
醉话见心
醉话见心 2020-11-28 21:33

I have the following ES6 modules:

File network.js

export function getDataFromServer() {
  return ...
}

File widget.js<

相关标签:
8条回答
  • 2020-11-28 21:55

    I have found this syntax to be working:

    My module:

    // File mymod.js
    import shortid from 'shortid';
    
    const myfunc = () => shortid();
    export default myfunc;
    

    My module's test code:

    // File mymod.test.js
    import myfunc from './mymod';
    import shortid from 'shortid';
    
    jest.mock('shortid');
    
    describe('mocks shortid', () => {
      it('works', () => {
        shortid.mockImplementation(() => 1);
        expect(myfunc()).toEqual(1);
      });
    });
    

    See the documentation.

    0 讨论(0)
  • 2020-11-28 21:58

    See suppose I'd like to mock results returned from isDevMode() function in order to check to see how code would behave under certain circumstances.

    The following example is tested against the following setup

        "@angular/core": "~9.1.3",
        "karma": "~5.1.0",
        "karma-jasmine": "~3.3.1",
    

    Here is an example of a simple test case scenario

    import * as coreLobrary from '@angular/core';
    import { urlBuilder } from '@app/util';
    
    const isDevMode = jasmine.createSpy().and.returnValue(true);
    
    Object.defineProperty(coreLibrary, 'isDevMode', {
      value: isDevMode
    });
    
    describe('url builder', () => {
      it('should build url for prod', () => {
        isDevMode.and.returnValue(false);
        expect(urlBuilder.build('/api/users').toBe('https://api.acme.enterprise.com/users');
      });
    
      it('should build url for dev', () => {
        isDevMode.and.returnValue(true);
        expect(urlBuilder.build('/api/users').toBe('localhost:3000/api/users');
      });
    });
    

    Exemplified contents of src/app/util/url-builder.ts

    import { isDevMode } from '@angular/core';
    import { environment } from '@root/environments';
    
    export function urlBuilder(urlPath: string): string {
      const base = isDevMode() ? environment.API_PROD_URI ? environment.API_LOCAL_URI;
    
      return new URL(urlPath, base).toJSON();
    }
    
    0 讨论(0)
提交回复
热议问题