文章目录
断言
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");
});