const {<!-- --> myFunc } = require('does not exist') jest.mock('does not exist', () => ({<!-- --> myFunc: () => 'hello', obj: {<!-- -->} }), {<!-- --> virtual: true } ); test('mock file that does not exist', () => {<!-- --> expect(myFunc()).toBe('hello') })
模拟Taro的login API
jest.mock('@tarojs/taro', () => {<!-- --> const login = jest.fn(async (): Promise<{<!-- --> code: string;errMsg: string }> => {<!-- --> return Promise.resolve({<!-- --> code: '122321121', errMsg: 'is:ok' }) }) return {<!-- --> ...jest.requireActual('@tarojs/taro-h5'), login } })
// myClass.js class MyClass {<!-- --> constructor(name) {<!-- --> this.name = name; } methodOne() {<!-- --> return 1; } methodTwo() {<!-- --> return 2; } } export default MyClass;
jest.mock('./myClass', () => () => ({<!-- --> name: 'Jody', methodOne: () => 10, methodTwo: () => 25, }));
export class MockedClass {<!-- --> public instanceMethod(): string {<!-- --> return "instance"; } public static staticMethod(): string {<!-- --> return "static"; } }
import {<!-- -->MockedClass} from './mocked-class' jest.mock('./mocked-class'); describe('TestClass', () => {<!-- --> it ('should mock instance method', () => {<!-- --> const expectedValue: string = 'instanceMocked' MockedClass.mockImplementation(() => {<!-- --> return {<!-- --> instanceMethod: () => expectedValue }; }); const actualValue: string = new TestClass().callStaticMethod(); expect(actualValue).toBe(expectedValue); }); it ('should mock static method', () => {<!-- --> const expectedValue: string = 'staticMocked' MockedClass.staticMethod.mockImplementation(() => expectedValue); const actualValue: string = new TestClass().callStaticMethod(); expect(actualValue).toBe(expectedValue); }); });
原函数
async getMultipleNamespace() {<!-- --> const _ApolloConfig = SYSTEM_APOLLO_CONFING; // 数组 if (Array.isArray(_ApolloConfig)) {<!-- --> for (const i in _ApolloConfig) {<!-- --> await this.getSystem(_ApolloConfig[i]); } return; } // 对象中的某一项是数组 if (Array.isArray(_ApolloConfig.namespace)) {<!-- --> const _namespaces = _ApolloConfig.namespace; delete _ApolloConfig.namespace; for (const i in _namespaces) {<!-- --> await this.getSystem(Object.assign(_ApolloConfig, {<!-- --> namespace: _namespaces[i] })); } return; } // 单对象 await this.getSystem(); }
jest内容
describe('测试多重判断', () => {<!-- --> beforeEach(() => {<!-- --> jest.resetModules(); }); test('getMultipleNamespace——检测单个config单个namespace', async () => {<!-- --> jest.mock('../script/Config',()=>{<!-- --> const SYSTEM_APOLLO_CONFING = {<!-- --> appId: 'fedsystem', cluster: 'default', namespace: 'application' } return {<!-- --> ...jest.requireActual('../script/Config'), SYSTEM_APOLLO_CONFING } }) // 一定要重新执行一次 const apollo = require('../index'); const getSystem = apollo.getSystem; const fn = jest.fn(); apollo.getSystem = function (...ret) {<!-- --> getSystem(...ret); fn(); } await apollo.getMultipleNamespace(); // 检测该方法是否被调用即可 expect(fn).toHaveBeenCalledTimes(1); }) test('getMultipleNamespace——检测多个config', async () => {<!-- --> jest.mock('../script/Config',()=>{<!-- --> const SYSTEM_APOLLO_CONFING = [{<!-- --> appId: 'fedsystem', cluster: 'default', namespace: 'application' },{<!-- --> appId: 'fedsystem', cluster: 'default', namespace: 'default' }] return {<!-- --> ...jest.requireActual('../script/Config'), SYSTEM_APOLLO_CONFING } }) const apollo = require('../index'); const getSystem = apollo.getSystem; const fn = jest.fn(); apollo.getSystem = function (...ret) {<!-- --> getSystem(...ret); fn(); } await apollo.getMultipleNamespace(); // 检测该方法是否被调用即可 expect(fn).toHaveBeenCalledTimes(2); }) test('getMultipleNamespace——检测单个config多个namespace', async () => {<!-- --> jest.mock('../script/Config',()=>{<!-- --> const SYSTEM_APOLLO_CONFING = {<!-- --> appId: 'fedsystem', cluster: 'default', namespace: ['application', 'default'] } return {<!-- --> ...jest.requireActual('../script/Config'), SYSTEM_APOLLO_CONFING } }) const apollo = require('../index'); const getSystem = apollo.getSystem; const fn = jest.fn(); apollo.getSystem = function (...ret) {<!-- --> getSystem(...ret); fn(); } await apollo.getMultipleNamespace(); // 检测该方法是否被调用即可 expect(fn).toHaveBeenCalledTimes(2); }) })
const projectConfig = require(path.join(process.cwd(), 'config'));
jest.mock('../config', () => ({<!-- --> obj: {<!-- -->} }), {<!-- --> virtual: true } );
文件hello.js
console.log("Hello World");
文件hello.test.js
let outputData = ""; storeLog = inputs => (outputData += inputs); test("console log Hello World",() => {<!-- --> console["log"] = jest.fn(storeLog); require("./hello.js"); expect(outputData).toBe("Hello World"); });