异步模拟无法使用 Jest 工作,是否有更好的方法或更简单的方法 sinon.stub()
Async Mock Not Working using Jest , Is there a better way or easy way as sinon.stub()
我正在尝试使用 jest 进行模拟,下面是我正在尝试的伪代码,发现与 jest[=24= 的真正联系] 。请对开玩笑的嘲笑提出一些想法。我正在寻找类似于 sinon.stub()
并且可以使用 resolve()
.
轻松解决的问题
class ExampleService {
static get() {
agent.get("/examples")
}
}
示例商店:
class ExampleStore {
const examples = []
getExamples() {
ExperimentService.get().then((result) = > {
this.examples = result
})
}
}
测试用例:
describe("ExampleStore", () = > {
it("getExamples", () = > {
data = [{
test: "test"
}]
ExperimentService.get = jest.fn(() = > {
return new Promise((resolve) = > {
process.nextTick(resolve(data)
}) ExampleStore.getExamples() expect(ExampleStore.examples).toBe(data)
}
})
})
您可以使用 jest.mock
通过您自己的实现模拟 ExperimentService.get
:
import ExampleStore from './ExampleStore'
jest.mock('path/to/ExperimentService' () =>({
get: ()=> return Promise.resolve({test: 'test'});
//get: ()=> {then: (fn)=> fn({test: 'test'})} if you don't want to mess with promises in your test
}))
describe("ExampleStore", () => {
it("getExamples", () => {
ExampleStore.getExamples()
expect(ExampleStore.examples).toBe(data)
}
})
})
我不确定它是否可以在存根中使用真正的承诺,因为通常您需要等待承诺得到解决,并且 return 我们使用异步等待的测试承诺。看看 how to handle promises。
因此,要么使用注释掉解决方案来模拟 get
或 return 承诺
在ExampleStore.getExample
中,以便您在测试中等待它。
我正在尝试使用 jest 进行模拟,下面是我正在尝试的伪代码,发现与 jest[=24= 的真正联系] 。请对开玩笑的嘲笑提出一些想法。我正在寻找类似于 sinon.stub()
并且可以使用 resolve()
.
class ExampleService {
static get() {
agent.get("/examples")
}
}
示例商店:
class ExampleStore {
const examples = []
getExamples() {
ExperimentService.get().then((result) = > {
this.examples = result
})
}
}
测试用例:
describe("ExampleStore", () = > {
it("getExamples", () = > {
data = [{
test: "test"
}]
ExperimentService.get = jest.fn(() = > {
return new Promise((resolve) = > {
process.nextTick(resolve(data)
}) ExampleStore.getExamples() expect(ExampleStore.examples).toBe(data)
}
})
})
您可以使用 jest.mock
通过您自己的实现模拟 ExperimentService.get
:
import ExampleStore from './ExampleStore'
jest.mock('path/to/ExperimentService' () =>({
get: ()=> return Promise.resolve({test: 'test'});
//get: ()=> {then: (fn)=> fn({test: 'test'})} if you don't want to mess with promises in your test
}))
describe("ExampleStore", () => {
it("getExamples", () => {
ExampleStore.getExamples()
expect(ExampleStore.examples).toBe(data)
}
})
})
我不确定它是否可以在存根中使用真正的承诺,因为通常您需要等待承诺得到解决,并且 return 我们使用异步等待的测试承诺。看看 how to handle promises。
因此,要么使用注释掉解决方案来模拟 get
或 return 承诺
在ExampleStore.getExample
中,以便您在测试中等待它。