以下源代码来自一本书。我写评论是为了更好地理解代码。
describe('window.foo', () => {
afterEach(() => {
delete global.foo // make sure you clean your global object after each test
})
it('should be called twice', () => {
const fooSpy = jest.fn();
const barSpy = jest.fn();
Object.defineProperty(global, 'foo', {
configurable: true, // very important or else you can't delete
get() {
fooSpy(); //we manually call our spy so we can assert later
// and we return an object with another spy for our bar function
return { bar: barSpy};
}
});
if (global.foo) {
global.foo.bar()
}
expect(fooSpy).toHaveBeenCalledTimes(2);
expect(barSpy).toHaveBeenCalledTimes(1);
});
it('should be called once', () => {
const fooSpy = jest.fn();
Object.defineProperty(global, 'foo', {
writconfigurableable: true,
get() {
fooSpy(); // we trigger the spy manually
// we return undefined
return undefined;
}
});
if (global.foo) {
global.foo.bar()
}
expect(fooSpy).toHaveBeenCalledTimes(1);
});
});
我对这个源代码有些困惑。
为什么#==================================================================
# markov(init,mat,n,states) = Simulates n steps of a Markov chain
#------------------------------------------------------------------
# init = initial distribution
# mat = transition matrix
# labels = a character vector of states used as label of data-frame;
# default is 1, .... k
#-------------------------------------------------------------------
markov <- function(init,mat,n,labels)
{
if (missing(labels)) # check if 'labels' argument is missing
{
labels <- 1:length(init) # obtain the length of init-vecor, and number them accordingly.
}
simlist <- numeric(n+1) # create an empty vector of 0's
states <- 1:length(init)# ???? use the length of initial distribution to generate states.
simlist[1] <- sample(states,1,prob=init) # sample function returns a random permutation of a vector.
# select one value from the 'states' based on 'init' probabilities.
for (i in 2:(n+1))
{
simlist[i] <- sample(states, 1, prob = mat[simlist[i-1],]) # simlist is a vector.
# so, it is selecting all the columns
# of a specific row from 'mat'
}
labels[simlist]
}
#==================================================================
用于生成状态?如果状态如 S = {-1,0,1,2,...} 该怎么办?
答案 0 :(得分:1)
S的确切标签由输入标签表示。
状态用作索引,在最后一行中,从1到states <- 1:length(init)
的状态的simlist被用作索引以提取正确的标签。