大多数情况下(就像你的情况一样)使用 map 是比使用 switch 更好的选择。
function f(){
var myInteger = syncApiCallReturnsInteger();
var map = {
0: "Some Text",
1: "Some Other Text",
2: "Another Text"
};
store.p1 = map[myInteger];
}
如果你想对此进行测试,你必须模拟出 syncApiCallReturnsInteger()。为了做到这一点,它必须是可注射的。商店也必须是可注入的,所以你可以检查它的变化。
function f(syncApiCallReturnsInteger, store){
var myInteger = syncApiCallReturnsInteger();
var map = {
0: "Some Text",
1: "Some Other Text",
2: "Another Text"
};
store.p1 = map[myInteger];
}
测试:
describe("blah", function() {
it("f sets store.p1", function() {
var fixture2expectation = {
0: "Some Text",
1: "Some Other Text",
2: "Another Text"
};
for (var fixtureString in fixture2expectation){
var fixture = parseInt(fixtureString);
var expectation = fixture2expectation[fixture];
var mockApiCall = function (){return fixture;};
var mockStore = {};
f(mockApiCall, mockStore);
expect(mockStore.p1).toBe(expectation);
}
});
});
如果您没有正确注入依赖项,那么您唯一能做的就是使用和覆盖全局变量,这通常是个坏主意,因为随着项目的发展,以后会出现变量名冲突。