[英]How do you write a Jest test to check if code execution is blocked?
我正在使用async-mutex
我只是想测试它的功能我想确认Mutex.acquire
方法是否保持阻塞。
it('should remain blocked when accessing the mutex a second time', async () => {
const mutex = new Mutex();
const release = await mutex.acquire();
expect(mutex.isLocked()).toBeTruthy();
expect( async () => { await mutex.acquire() } ).toStillBeRunningAfterSpecifiedSeconds(5);
});
我试过了
expect(await mutex.acquire()).toThrow("Timeout");
自从我收到这条消息
超时 - 在 jest.setTimeout.Timeout 指定的 5000 毫秒超时内未调用异步回调 - 在 jest.setTimeout.Error 指定的 5000 毫秒超时内未调用异步回调:
但没有运气。
这是您可以做到的一种方法:
describe("async-mutex", () => {
it("checks that lock is released", (done) => {
const mutex = new Mutex();
// releases the lock right after locking it
mutex.acquire().then((release) => {
release();
expect(mutex.isLocked()).toBe(false);
done();
});
});
it("checks that lock is not released", (done) => {
// if test is running after 4 seconds, then mutex is still locked
// done exits this test without errors
setTimeout(() => {
done();
}, 4000);
const mutex = new Mutex();
mutex.acquire();
expect(mutex.isLocked()).toBe(true);
// this second call to acquire should never run
// if it does, then the test should fail
mutex.acquire().then(() => {
expect(1).toBe(2);
});
});
});
现在,如果您的问题在于测试的持续时间,您可以随时使用jest.setTimeout(milliseconds)
来增加它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.