假设我有一个文件file1.js
,其中包含:
const a = true;
let b;
if (a) {
b = c;
}
if (!a) {
b = d;
}
现在当我在这个文件上运行测试用例时,我的第一个条件就被覆盖了。有没有什么方法可以通过将a
设置为false来覆盖第二个条件,或者我应该以一种方式更改我的代码,我可以调用具有不同值的方法来测试每种情况类似:
const a = true;
getBVal(a) {
return a ? c : d;
}
let b = getBVal(a);
更新
以下是我的带有旧版浏览器后备的requestAnimationFrame的代码:
let lastTime = 0;
const vendors = ["ms", "moz", "webkit", "o"];
let rAF = window.requestAnimationFrame;
if (!rAF) {
rAF = vendors.find(prefix => window[`${prefix}RequestAnimationFrame`]);
}
if (!rAF) {
rAF = cB => {
const currTime = new Date().getTime();
const timeToCall = Math.max(0, 16 - (currTime - lastTime));
const id = setTimeout(() => {
cB(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
function requestAnimationFrame(callback) {
return rAF(callback);
}
export default requestAnimationFrame;
我在窗口对象的设置中使用jsdom。现在,如果我必须测试window.requestAnimationFrame = null
的案例,那么我编写代码的方式就不可能了
现在将其更改为:
import { requestAnimationFrameVendor } from "../constants";
let lastTime = 0;
const customFn = cB => {
const currTime = new Date().getTime();
const timeToCall = Math.max(0, 16 - (currTime - lastTime));
const id = setTimeout(() => {
cB(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
function requestAnimationFrame(callback) {
const rAF = window.requestAnimationFrame;
return rAF && rAF(callback) || requestAnimationFrameVendor && requestAnimationFrameVendor(callback) || customFn(callback);
}
export default requestAnimationFrame;
然后如果我写测试如下:
import * as constants from "../../constants";
describe("animationFrame", () => {
let requestAnimationFrame;
let cancelAnimationFrame;
beforeAll(() => {
requestAnimationFrame = global.window.requestAnimationFrame;
cancelAnimationFrame = global.window.cancelAnimationFrame;
});
test("requestAnimationFrame", done => {
global.window.requestAnimationFrame = null;
global.window.cancelAnimationFrame = null;
const requestId1 = Utils.requestAnimationFrame(jest.fn());
constants.requestAnimationFrameVendor = jest.fn(() => {
return requestAnimationFrame;
});
const requestId2 = Utils.requestAnimationFrame(jest.fn());
setTimeout(() => {
Utils.cancelAnimationFrame(requestId1);
Utils.cancelAnimationFrame(requestId2);
done();
}, 300);
});
afterEach(() => {
global.window.webkitRequestAnimationFrame = null;
global.window.webkitCancelAnimationFrame = null;
});
});
然后它涵盖了所有条件。
答案 0 :(得分:1)
我会去第二次溃败(getBVal()
)因为它使你的界面更容易测试。
通常,删除全局状态(如const a
或let b
)将使您的代码和接口更易于测试。如果您无法完全删除全局状态,则可以引入抽象,以便您的测试不需要了解全局状态(如建议的getBVal()
)。
也许您可以更进一步,删除全球b
:而是始终致电getBVal()
?在大多数情况下,性能影响可以忽略不计,而且您的代码变得更加可测试且耦合性更低......