Jest: setSystemTime is not available when not using modern timers - jestjs

Here is the code. I'm getting error TypeError: setSystemTime is not available when not using modern timers when I run the test. I have "#jest/fake-timers": "^27.4.2" in my package.json since I thought there could be a conflict on the package in some dependencies, but issue remains
beforeAll(() => {
jest.useFakeTimers('modern');
jest.setSystemTime(new Date());
});
afterAll(() => {
jest.useRealTimers();
});
Any idea how to resolve this?

As mentioned in this issue, it can be solved by checking the version of jest and it's related packages. For example, I had jest on version 26.6.0 and babel-jest and ts-jest on 27.x. Setting them to 26.x solved the problem.

Facing the same issue here, this patch from #stereodenis is working (copying it here):
let dateNowSpy: jest.SpyInstance;
const today = new Date('2000-01-01').getTime();
describe('...', () => {
beforeEach(() => {
dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => today);
});
afterEach(() => {
dateNowSpy.mockRestore();
});
test('...', () => {
/* Date.now() -> 2000-01-01 */
});

Related

How to fix jest/no-standalone-expect coming from Cypress test?

I have E2E Cypress tests and they all pass. However this one gives me a jest/no-standalone-expect ESLint error:
Then(/^I should see a headline "(.+)"/, title => {
cy.get('#Request').then((interception: unknown) => {
const interceptedRequest = interception;
cy.get(stuff[title]).then(heading => {
expect(heading).to.match(new RegExp(interceptedRequest.thing));
})
});
});
I have similar uses of expect in other tests without issues. How do I fix this one and what's causing the issue?
This is what eventually solved my issue - extracting the expect into a helper function.
Then(/^I should see a headline "(.+)"/, title => {
const matchHelper = (text, test) => {
expect(text).to.match(test)
}
cy.get('#Request').then((interception: unknown) => {
const interceptedRequest = interception;
cy.get(stuff[title]).then(heading => {
matchHelper(heading, new RegExp(interceptedRequest.thing));
})
});
});
It's one of the suggestions from the official docs, but still doesn't make much sense to me.

Promise objects not working in React Native project

First, I thought firebase functions were broken. Then, I tried to make a simple function that returns Promise. I put that to top-level index.js.
const testPromise = param => {
console.log('return promise', param);
return new Promise((resolve, reject) => {
console.log('resolve promise');
resolve('derp');
});
};
testPromise('hede')
.then(d => {
console.log('resolved');
})
.catch(e => {
console.log('e', e);
});
AppRegistry.registerComponent(appName, () => App);
Console output:
return promise hede
resolve promise
See, there is no 'resolved' log nor error log.
I tried to change nodejs versions with nvm but no luck. I tried v12.5.0, v12.18.2, v15.6.0, v10.16.3. I tried like nvm use 12.5 && npm start
I've tried to create a new react-native project and I copied everything. Now, it works as expected. It is a solution for me but I didn't mark the question as solved because there is still a mystery, I couldn't figure why it doesn't work on the existing project.
It seems that setting inlineRequires to false inside the metro.config.js file resolves the issue.
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
After making that change the output is:
return promise hede
resolve promise
resolved
Source: https://github.com/facebook/react-native/issues/31558#issuecomment-878342213

isVueInstance is deprecated and will be removed in future releases

I am new with JEST and have received the above warning. I want to know which is the alternative since is being deprecated.
Here is the test that I am making:
it('is instantiated', () => {
expect(wrapper.isVueInstance()).toBeTruthy();
});
Here's how to rigorously check VueInstance
https://github.com/vuejs/vue-test-utils/blob/2d6b49780c7e1d663b877ddf5d6492ed7b510379/packages/test-utils/src/wrapper.js#L400
it('is instantiated', () => {
expect(wrapper.vm).toBeTruthy();
});
I have checked https://vue-test-utils.vuejs.org/api/wrapper/#isvisible and they say:
Assert Wrapper is Vue instance.
So the final thing would be:
it('is instantiated', () => {
expect(wrapper).toBeTruthy();
});
The right answer should be the following:
it('is instantiated', () => {
expect(wrapper.exists()).toBeTruthy();
});
From test/specs/wrapper/find.spec.js in vue-test-utils repository,
you can see that when wrapper doesnt exists they assert Wrapper object with exists().
it('returns empty Wrapper with error if no nodes are found', () => {
const wrapper = mountingMethod(Component)
const selector = 'pre'
const error = wrapper.find(selector)
expect(error.exists()).toEqual(false)
expect(error.selector).toEqual(selector)
})

How to use jest.each asynchronously

I am having problems loading filenames into jest.each asynchronously.
My code:
let files: string[][]
function getFilesWorking() {
files = [["test1"], ["test2"]]
}
async function getFilesAsync() {
files = await Promise.resolve([["test1"], ["test2"]])
}
beforeAll(() => {
console.log("before")
})
describe.only("Name of the group", () => {
getFilesAsync()
test.each(files)("runs", f => {})
})
beforeAll is executed before each test but NOT before initialization of test.each, so I end up with undefined.
How can I load files before using test.each?
You can pass an async callback to beforeAll and await getFilesAsync within it
beforeAll(async () => {
await getFilesAsync();
})
As of Jest 28.1.3 and prior, this is not possible. There is an open issue documenting this behavior.
The best thing you can do for now is put your tests in a regular it() test and do a deep value comparison:
it('tests an array of cases', async () => {
const data = await getSomeAsyncData()
const expectedData = [ ... ]
expect(data).toEqual(expectedData)
})
You can use beforeEach to set up code that will run prior to tests for any given scope, https://jestjs.io/docs/setup-teardown:
beforeEach(() => {
console.log('before every test');
});
describe.only(('Name of the group') => {
beforeEach(() => {
console.log('before tests in this describe block');
})
})
Jest is only going to run the tests in your describe.only block. If you want to use beforeEach in other blocks and run those tests as well, change describe.only to describe.
(Edit: I know this is a year late, I'm just trying to look for a similar problem/solution set and thought I could answer this.)

Failing expect() inside subscribe() does not mark test as invalid

We recently upgraded to Angular 6.0.3, RxJs 6.2.0 and jest 23.1.0 (upgrading from RxJS 5 & Angular 4).
There seems to be a problem with Jest & RxJs as failing expect-statements inside a subscribe-Block do not mark the test as failed. Here's a minimal example:
it("should fail", () => {
const obs = Observable.create((observer) => {
observer.next(false);
});
obs.subscribe((value) => {
console.log(value); // => false
expect(value).toBeTruthy();
});
});
The expect-Statement gets executed, but the test still passes. We didn't observe this behaviour with the previous RxJs version and Jest.
Try to use done.
it("should fail", (done) => {
const obs = Observable.create((observer) => {
observer.next(false);
});
obs.subscribe((value) => {
console.log(value); // => false
expect(value).toBeTruthy();
done();
});
});
more info

Resources