jest单测知多少

断言

mock内容

mock一个不存在的文件

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')
})

mock模块中的某个功能,并且保留模块原有的功能

模拟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
  }
})

mock一个类

// 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,
}));

mock类的静态方法

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);
  });
});

检测多个判断,多次mock一个内容

原函数

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);
    })
})

mock process.cwd()内容

const projectConfig = require(path.join(process.cwd(), 'config'));
jest.mock('../config',
    () => ({
        obj: {}
    }),
    { virtual: true }
);

特殊处理

检测console.log

文件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"); 
}); 
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jest一个流行的 JavaScript 测试框架,可以用于编写元测试、集成测试和端到端测试。下面是 Jest 元测试入门的步骤: 1. 安装 Jest 使用 npm 安装 Jest:`npm install --save-dev jest` 2. 编写测试用例 在项目根目录下创建一个名为 `__tests__` 的文件夹,并在其中创建一个名为 `example.test.js` 的文件。在 `example.test.js` 文件中编写测试用例: ```javascript describe('示例测试', () => { test('测试1', () => { expect(1 + 1).toBe(2); }); test('测试2', () => { expect(true).toBeTruthy(); }); }); ``` 上面的代码定义了一个测试套件 `示例测试`,其中包含两个测试用例 `测试1` 和 `测试2`。每个测试用例都是一个函数,其中包含一个或多个 `expect` 语句,用于断言测试结果是否符合预期。 3. 运行测试 在命令行中输入 `npx jest` 命令,Jest 将自动查找项目中的测试用例并运行它们。如果所有测试用例都通过,Jest 将输出一个绿色的提示。 4. 高级配置 Jest 提供了丰富的配置选项,可以用于定制测试过程。例如,可以在 `package.json` 文件中添加以下配置: ```json { "jest": { "testEnvironment": "node", "testMatch": [ "**/__tests__/**/*.test.js" ], "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": 80 } } } } ``` 上面的配置指定了测试环境为 Node.js,测试文件必须位于 `__tests__` 文件夹中,并以 `.test.js` 结尾。还指定了代码覆盖率的阈值,如果代码覆盖率低于指定的阈值,Jest 将会提示测试失败。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值