之前给出的所有回复均未正确使用expect()
在他们的实施中,所以他们并没有真正发挥作用。
你想要的是一个笑话匹配器,其工作原理如下any()
但接受空值并且不使用expect()
其实施中的职能。您可以通过基本上复制原始内容来实现它作为扩展any()
实施(从Jasmine https://github.com/jasmine/jasmine/blob/master/src/core/asymmetric_equality/Any.js),但在开头添加了一个空测试:
expect.extend({
nullOrAny(received, expected) {
if (received === null) {
return {
pass: true,
message: () => `expected null or instance of ${this.utils.printExpected(expected) }, but received ${ this.utils.printReceived(received) }`
};
}
if (expected == String) {
return {
pass: typeof received == 'string' || received instanceof String,
message: () => `expected null or instance of ${this.utils.printExpected(expected) }, but received ${ this.utils.printReceived(received) }`
};
}
if (expected == Number) {
return {
pass: typeof received == 'number' || received instanceof Number,
message: () => `expected null or instance of ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`
};
}
if (expected == Function) {
return {
pass: typeof received == 'function' || received instanceof Function,
message: () => `expected null or instance of ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`
};
}
if (expected == Object) {
return {
pass: received !== null && typeof received == 'object',
message: () => `expected null or instance of ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`
};
}
if (expected == Boolean) {
return {
pass: typeof received == 'boolean',
message: () => `expected null or instance of ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`
};
}
/* jshint -W122 */
/* global Symbol */
if (typeof Symbol != 'undefined' && this.expectedObject == Symbol) {
return {
pass: typeof received == 'symbol',
message: () => `expected null or instance of ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`
};
}
/* jshint +W122 */
return {
pass: received instanceof expected,
message: () => `expected null or instance of ${this.utils.printExpected(expected)}, but received ${this.utils.printReceived(received)}`
};
}
});
将以上内容放入.js
文件,然后开玩笑地指向该文件setupFilesAfterEnv https://jestjs.io/docs/en/configuration#setupfilesafterenv-array配置变量。现在您可以运行测试,例如:
const schema = {
person: expect.nullOrAny(Person),
age: expect.nullOrAny(Number)
};
expect(object).toEqual(schema);