I'm writing some tests against a card game I made in JS using Jest.
I wrote two tests so far; one testing a deck of 52 cards are created and the other tests if the player is drawn two cards at the opening round:
const { Deck, Player} = require("./cardgame")
let deck = new Deck()
deck = deck.createDeck()
let player = new Player()
player.openinghand(deck)
test('Expects Deck to have 52 cards', () => {
expect(deck.length).toBe(52);
});
test('Expects Players opening hand to have 2 cards', () => {
expect(player.hand.length).toBe(2)
});
So when I run the test, only the second one passes. I understand why it's failing because the deck length is no longer equal to 52. Does Jest run all the tests simultaneously and not in the order that they're written? How would I get this to pass both tests?
CodePudding user response:
Unit tests should be idempotent. Regardless of the order of execution and how many times it is executed, the result should be the same.
You need to make sure the test environment, test double, test data are independent for each test case.
From your code, it seems that those two test cases share one test data. This can lead to the potential risk that a test case modifying it will affect other test case.