繁体   English   中英

JavaScript单元测试-从玩笑虚拟模拟中返回不同的对象

[英]javascript unit testing - return different objects from jest virtual mocks

我有一个玩笑的单元测试,它使用了虚拟模拟。

虚拟模拟返回apiName =“ standard__abc”的对象

我测试了一个函数(isApiNameABC()),如果apiName ===“ standard__abc”,则使用模拟的对象返回true,否则返回false。

使用下面的代码,我可以测试返回true的条件...

我的问题是,如何修改测试代码,以便虚拟模拟返回apiName的其他值。 我要执行此操作以测试isApiNameABC()返回false的情况。

import * as utils from '../utils';

jest.mock('mdl/appContextService', () => {
    return { 
        appContext: {
            apiName: "standard__abc"
        }
    }
}, {virtual: true});

describe("utils", () => { 
    test("test return value of apiName is EQUAL to standard__abc", () => {
        expect(utils.isApiNameABC()).toEqual(true);      
    });
});

apiName只是模块导出中的一个属性,因此您可以直接对其进行更改。

假设utils.js看起来像这样:

import { appContext } from 'mdl/appContextService';

export const isApiNameABC = () => appContext.apiName === 'standard__abc';

您可以像这样测试它:

import * as utils from './utils';
import { appContext } from 'mdl/appContextService';

jest.mock('mdl/appContextService', () => {
  return {
    appContext: {
      apiName: "standard__abc"
    }
  }
}, { virtual: true });

describe("utils", () => {
  test("test return value of apiName is EQUAL to standard__abc", () => {
    expect(utils.isApiNameABC()).toEqual(true);  // Success!
  });
  test("test return value of apiName is NOT EQUAL to standard__abc", () => {
    const original = appContext.apiName;
    appContext.apiName = 'something else';  // <= change it directly
    expect(utils.isApiNameABC()).toEqual(false);  // Success!
    appContext.apiName = original;  // <= restore it
  });
});

如果apiName是一个函数,则可以使用模拟函数并更改其返回值:

import * as utils from './utils';
import { appContext } from 'mdl/appContextService';

jest.mock('mdl/appContextService', () => {
  return {
    appContext: {
      apiName: jest.fn(() => "standard__abc")  // <= use a mock function
    }
  }
}, { virtual: true });

describe("utils", () => {
  test("test return value of apiName is EQUAL to standard__abc", () => {
    expect(utils.isApiNameABC()).toEqual(true);  // Success!
  });
  test("test return value of apiName is NOT EQUAL to standard__abc", () => {
    appContext.apiName.mockReturnValue('something else');  // <= change the return value
    expect(utils.isApiNameABC()).toEqual(false);  // Success!
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM